package com.siwei.mes.service.laboratory.impl;


import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.ConvertUtils;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.UploadFlagUtils;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.UploadLaboratoryEntity;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraExtend;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.ExperimentGenConfig;
import com.siwei.mes.entity.experiment.ExperimentItemorder;
import com.siwei.mes.entity.experiment.cement.CementBbmj;
import com.siwei.mes.entity.experiment.cement.CementMd;
import com.siwei.mes.entity.experiment.cement.CementXd;
import com.siwei.mes.entity.experiment.coarseAggregate.CoarseAggregateBgmd;
import com.siwei.mes.entity.experiment.coarseAggregate.CoarseAggregateDjmd;
import com.siwei.mes.entity.experiment.coarseAggregate.CoarseAggregateJmmd;
import com.siwei.mes.entity.experiment.coarseAggregate.CoarseAggregateYszzb;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKsdj;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKyqd;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKzqd;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureJSL;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureNjsjzc;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureQslb;
import com.siwei.mes.entity.experiment.concreteAdmixture.ConcreteAdmixtureTld1hjsbhl;
import com.siwei.mes.entity.experiment.fineAggregate.*;
import com.siwei.mes.entity.experiment.flyAsk.FlyAskHdzs;
import com.siwei.mes.entity.experiment.flyAsk.FlyAskSyhl;
import com.siwei.mes.entity.experiment.flyAsk.FlyAskYlyhg;
import com.siwei.mes.entity.experiment.slag.SlagBbmj;
import com.siwei.mes.entity.experiment.slag.SlagHsl;
import com.siwei.mes.entity.experiment.slag.SlagSsl;
import com.siwei.mes.entity.experiment.slag.SlagYpmd;
import com.siwei.mes.entity.laboratory.*;
import com.siwei.mes.entity.laboratory.concrete.SampleUcHnt;
import com.siwei.mes.entity.materials.MaterialsSpecConfig;
import com.siwei.mes.entity.system.SupplierCompanyMaterials;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.erp.RwdextraExtendMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentGenConfigMapper;
import com.siwei.mes.mapper.experiment.ExperimentItemorderMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.laboratory.*;
import com.siwei.mes.mapper.materials.MaterialsSpecConfigMapper;
import com.siwei.mes.mapper.materials.SupplierCompanyMaterialsMapper;
import com.siwei.mes.mapper.system.TestProjectInfoMapper;
import com.siwei.mes.service.erp.RwdextraService;
import com.siwei.mes.service.experiment.ExperimentSampleTakeService;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.service.laboratory.TaskListLaboratoryService;
import com.siwei.mes.service.laboratory.UploadLaboratoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

@Service
public class UploadLaboratoryServiceImpl implements UploadLaboratoryService {
    private static final Logger log = LoggerFactory.getLogger("laboratory");
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private UploadLaboratoryMapper m_uploadLaboratoryMapper;
    @Resource
    private TestProjectInfoMapper testProjectInfoMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private WTSampleMapper wtSampleMapper;
    @Resource
    private WTConsignMapper wtConsignMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;
    @Resource
    private RwdextraExtendMapper rwdextraExtendMapper;
    @Resource
    private RwdextraService rwdextraService;
    @Resource
    private DataHntPhbMapper dataHntPhbMapper;
    @Resource
    private SupplierCompanyMaterialsMapper supplierCompanyMaterialsMapper;
    @Resource
    private WTConsignWithSampleMapper wtConsignWithSampleMapper;
    @Resource
    private ExperimentItemorderMapper experimentItemorderMapper;
    @Resource
    private ExperimentSampleTakeService experimentSampleTakeService;
    @Resource
    private SampleMapper sampleMapper;
    @Resource
    private ImportListMapper importListMapper;
    @Resource
    private WTCurrentIdMapper wtCurrentIdMapper;
    @Resource
    private KeyPropertyMapper keyPropertyMapper;
    @Resource
    private MaterialsSpecConfigMapper materialsSpecConfigMapper;
    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private DataDefUcLaboratoryMapper dataDefUcLaboratoryMapper;
    @Resource
    private TaskListLaboratoryService taskListLaboratoryService;

    @Override
    public void incomingMaterials(UploadLaboratoryEntity entity) {
        try {
            assertTrue(entity == null || entity.getExptId() == null, "上传上海协会入场操作数据，试验台账id不允许为空！");

            //需要同步的试验台账数据 id
            //根据品控台账id 查询上海协会sampleNo
            Experiment experiment = experimentService.loadById(entity.getExptId());

            //过滤快检业务
            if (experiment.getCheckType() == null || experiment.getCheckType().equals(CheckEnum.QUICK.getCode())) {
                log.error("不允许同步快检业务... 台账id：" + experiment.getId());
                throw new RuntimeException("不允许同步快检业务... 台账id：" + experiment.getId());
            }

            log.info("同步新增原材料进料开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());

            //生成sampleNo
            String sampleNo = generateNew(experiment, new ArrayList<>());

            if (sampleNo == null) {
                log.error("生成的sampleNo 为空！：" + sampleNo);
                return;
            }
            //材料进场
            ImportList importList = materialEntry(experiment, sampleNo);

            if (importList == null) {
                log.error("材料进场数据有误 为空！：importList = " + importList);
                throw new RuntimeException("材料进场数据有误 为空！：importList = " + importList);
            }

            log.info("同步新增原材料进料结束，协会进料编码：【{}】", importList.getImportId());

            //查询上传协会状态
            ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experiment.getId());
            if (shxhInfo == null) {
                //新增对应关系
                ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata()
                        .setSampleNo(sampleNo).setImportId(importList.getImportId()).setExperimentId(experiment.getId());
                shxhSynchronizedataMapper.insertSelective(synchronizedata);
            } else {
                shxhInfo.setSampleNo(sampleNo).setImportId(importList.getImportId());
                shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException("新增协会原材料入场进料失败" + e.getMessage());
        }
    }

    @Override
    public void updateIncomingMaterials(UploadLaboratoryEntity entity, String importId) {
        try {
            assertTrue(entity == null || entity.getExptId() == null, "上传上海协会入场操作数据，试验台账id不允许为空！");

            //需要同步的试验台账数据 id
            //根据品控台账id 查询上海协会sampleNo
            Experiment experiment = experimentService.loadById(entity.getExptId());

            //过滤快检业务
            if (experiment.getCheckType() == null || experiment.getCheckType().equals(CheckEnum.QUICK.getCode())) {
                log.error("不允许同步快检业务... 台账id：" + experiment.getId());
                throw new RuntimeException("不允许同步快检业务... 台账id：" + experiment.getId());
            }

            //材料进场
            updateMaterialEntry(experiment, importId);


        } catch (Exception e) {
            throw new RuntimeException("修改协会原材料入场进料失败" + e.getMessage());
        }
    }


    /**
     * 生成上海协会台账
     *
     * @param entity 实验室实体，包含试验台账信息
     * @throws RuntimeException 如果生成台账过程中发生错误
     */
    @Override
    public void generateLedger(UploadLaboratoryEntity entity) {
        try {
            // 检查试验台账id是否为空，如果为空则抛出异常
            if (entity == null || entity.getExptId() == null) {
                throw new IllegalArgumentException("上传上海协会台账数据，试验台账id不允许为空！");
            }

            // 根据试验台账id获取需要同步的试验台账数据
            Experiment experiment = experimentService.loadById(entity.getExptId());

            // 过滤快检业务，如果试验类型为快检则抛出异常
            if (experiment.getCheckType() == null || experiment.getCheckType().equals(CheckEnum.QUICK.getCode())) {
                log.error("不允许同步快检业务... 台账id：" + experiment.getId());
                throw new Exception("不允许同步快检业务... 台账id：" + experiment.getId());
            }

            // 根据实验类型处理不同的业务逻辑
            // 混凝土
            if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
                handleConcreteExperiment(experiment);
            } else {
                handleOtherMaterialsExperiment(experiment);
            }
        } catch (Exception e) {
            // 捕获并重新抛出异常，提供更详细的错误信息
            log.error("新增/修改协会生成台账失败: " + e.getMessage(), e);
            throw new RuntimeException("新增/修改协会生成台账失败: " + e.getMessage(), e);

        }
    }

    /**
     * 处理混凝土实验的逻辑
     *
     * @param experiment 实验对象，包含实验的相关信息
     */
    private void handleConcreteExperiment(Experiment experiment) {
        try {
            // 查询与实验ID相关的同步数据列表
            List<ShxhSynchronizedata> list = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));
            log.error("查询协会上传数据结果{} 品控台账编码为{}", list, experiment.getId());
            // 判断列表是否为空或第一个元素的样品ID和委托ID是否为空，以决定是新增还是修改操作
            if (CollectionUtils.isEmpty(list) || StringUtils.isBlank(list.get(0).getSampleId()) || StringUtils.isBlank(list.get(0).getConsignId())) {
                // 如果列表为空或关键信息缺失，则记录日志并执行新增操作
                log.info("同步新增混凝土委托+样品开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());
                addTestLedgerHnt(experiment);
            } else {
                // 如果列表非空且关键信息存在，则取出第一个元素并执行修改操作
                ShxhSynchronizedata synchronizedata1 = list.get(0);
                log.info("同步修改混凝土委托+样品开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());
                updateTestLedgerHnt(experiment, synchronizedata1.getSampleId(), synchronizedata1.getConsignId());
            }
        } catch (Exception e) {
            log.error("UploadLaboratoryServiceImpl.java 处理混凝土实验的逻辑异常：{}", e.getMessage(), e);
        }
    }

    /**
     * 处理其他原材料实验的逻辑
     * 该方法主要用于同步上海协会数据，处理进料和取样，并更新相关记录
     *
     * @param experiment 实验对象，包含实验的相关信息
     */
    private void handleOtherMaterialsExperiment(Experiment experiment) {
        // 获取与实验ID相关的同步数据列表
        List<ShxhSynchronizedata> list = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));

        // 检查列表是否为空或关键字段是否为空，如果为空则抛出异常
        if (CollectionUtils.isEmpty(list) || list.get(0).getSampleNo() == null || list.get(0).getImportId() == null) {
            log.error("同步协会生成进料/取样可能未成功！... 台账id：" + experiment.getId());
            throw new RuntimeException("同步协会生成进料/取样可能未成功！... 台账id：" + experiment.getId());
        }

        // 获取第一个同步数据对象
        ShxhSynchronizedata synchronizedata1 = list.get(0);
        // 创建一个列表，包含第一个同步数据对象的ImportId
        List<String> importIds = Collections.singletonList(synchronizedata1.getImportId());
        // 根据ImportId查找进料列表
        List<ImportList> mapList = importListMapper.findImportListById(importIds);

        // 如果未找到对应的进料数据，抛出异常
        if (CollectionUtils.isEmpty(mapList)) {
            log.error("未查询到上海协会对应的进料数据！... ImportId=" + synchronizedata1.getImportId());
            throw new RuntimeException("未查询到上海协会对应的进料数据！... ImportId=" + synchronizedata1.getImportId());
        }

        // 获取第一个进料列表对象
        ImportList importList = mapList.get(0);
        // 如果进料数量为空，则设置为"0"
        if (StringUtils.isEmpty(importList.getProdinQuan())) {
            importList.setProdinQuan("0");
        }

        // 处理协会台账并获取委托ID
        String consignId = handleTestLedger(experiment, synchronizedata1, importList);

        // 如果委托ID不为空，则更新同步数据对象并保存到数据库
        if (StringUtils.isNotBlank(consignId)) {
            synchronizedata1.setConsignId(consignId);
            synchronizedata1.setSampleId(synchronizedata1.getSampleNo());
            shxhSynchronizedataMapper.updateByPrimaryKeySelective(synchronizedata1);
        }
    }

    /**
     * 此方法根据同步数据中的委托ID是否存在，决定是更新还是新增
     *
     * @param experiment       实验对象，包含实验相关信息
     * @param synchronizedata1 同步数据对象，包含与协会同步相关的数据
     * @param importList       协会进料对象
     * @return 返回新增协会的结果，如果是更新操作则返回null
     */
    private String handleTestLedger(Experiment experiment, ShxhSynchronizedata synchronizedata1, ImportList importList) {
        // 检查同步数据中的委托ID是否不为空
        if (StringUtils.isNotBlank(synchronizedata1.getConsignId())) {
            // 记录更新原材料委托的日志
            log.info("同步修改原材料委托开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());
            // 调用方法更新协会
            updateTestLedger(experiment, synchronizedata1.getSampleNo(), importList, synchronizedata1.getConsignId());
            return null;
        } else {
            // 记录新增原材料委托的日志
            log.info("同步新增原材料委托开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());
            // 调用方法新增协会并返回结果
            return addTestLedger(experiment, synchronizedata1.getSampleNo(), importList);
        }
    }

    @Override
    public void samplingOperation(UploadLaboratoryEntity entity) {
        try {
            assertTrue(entity == null || entity.getExptId() == null, "上传上海协会取样数据，试验台账id不允许为空！");

            //需要同步的试验台账数据 id
            List<String> experimentId = entity.getExperimentId();

            //根据品控台账id 查询上海协会sampleNo
            Experiment experiment = experimentService.loadById(entity.getExptId());

            //过滤快检业务
            if (experiment.getCheckType() == null || experiment.getCheckType().equals(CheckEnum.QUICK.getCode())) {
                log.error("不允许同步快检业务... 台账id：" + experiment.getId());
                throw new RuntimeException("不允许同步快检业务... 台账id：" + experiment.getId());
            }

            //查询是否同步进料
            List<ShxhSynchronizedata> list = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));

            if (list == null || list.size() == 0 || list.get(0).getSampleNo() == null || list.get(0).getImportId() == null /*|| list.get(0).getConsignId() == null*/) {
                log.error("同步协会生成进料/台账可能未成功！... 台账id：" + experiment.getId());
                throw new RuntimeException("同步协会生成进料/台账可能未成功！... 台账id：" + experiment.getId());
            }
            //查询协会进料id
            ShxhSynchronizedata synchronizedata1 = list.get(0);

            log.info("同步新增原材料样品开始，品控台账id：【{}】，台账编号；【{}】", experiment.getId(), experiment.getExperimentNo());

            //新增样品
            addSample(experiment, synchronizedata1.getSampleNo(), null, null);


            //修改进料数据为已取样
            importListMapper.updateImportList(synchronizedata1.getImportId());

            log.info("同步新增原材料样品结束，协会样品编号：【{}】", synchronizedata1.getSampleNo());
         /*   //修改对应关系
            synchronizedata1.setSampleId(synchronizedata1.getSampleNo());
            shxhSynchronizedataMapper.updateByPrimaryKeySelective(synchronizedata1);*/

        } catch (Exception e) {
            throw new RuntimeException("同步协会取样操作失败" + e.getMessage());
        }
    }

    @Override
    public void modifySpecifications(String sampleNo, Experiment experiment) {
        log.info("开始修改协会对应物料规格数据，sampleNo：【{}】，台账信息：【{}】", sampleNo, experiment);

        //根据台账 查询品控做的试验项目详情
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));
        //查询出品控的试验项目配置
        List<TestProjectInfo> testProjectInfoList = new ArrayList<>();
        //存储协会需要做的项目集合
        Set<String> set = new LinkedHashSet<>();

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            //查询出品控的水泥试验项目配置
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CEMENT.getTestProjectType()));
        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FLY.getTestProjectType()));
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.SLAG.getTestProjectType()));
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.COARSE.getTestProjectType()));
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FINE.getTestProjectType()));
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.ADMIXTURE.getTestProjectType()));
        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CONCRETE.getTestProjectType()));
        } else {
            log.error("未知的实验类型：【{}】", experiment.getExperimentType());
            return;
        }


        for (ExperimentDetail detail : list) {
            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                    if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {

                        //细骨料含泥量 特殊处理   含泥量默认对应三条协会试验  如果为天然砂 则直接取第一条  如果是机制砂则取第二第三条
                        if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode())) {

                            String[] split = testProjectInfo.getParameterName().split(",");

                            //机制砂
                            if (experiment.getMaterialsName() != null && ("混合砂".equals(experiment.getMaterialsName()) || "人工砂".equals(experiment.getMaterialsName()))) {
                                set.add(split[1]);
                                set.add(split[2]);
                                //天然砂
                            } else {
                                set.add(split[0]);
                            }
                        } else {
                            //添加进协会需要做的项目集合
                            set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                        }
                    }
                }
            }

        }

        //如果所有项目都没做 则不生成协会台账信息
        if (set.isEmpty()) {
            return;
        }

        //根据样品编号查询未修改前的规格
        Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);
        if (wtSampleList == null || wtSampleList.get("SampleID") == null) {
            log.info("修改原材料规格信息时出现错误，未查询到协会样品数据，样品id:", sampleNo);
            return;
        }
        //未修改前的样品id
        String oldSampleID = wtSampleList.get("SampleID").toString();
        log.info("未修改前的SampleID: {}", oldSampleID);


        Long spId = experiment.getSpecId();

        if (spId == null) {
            log.error("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
            throw new RuntimeException("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
        }
        //查询对应同步的协会材料数据
        MaterialsSpecConfig materialsSpecConfig = materialsSpecConfigMapper.loadById(spId);

        if (materialsSpecConfig == null) {
            log.error("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
            throw new RuntimeException("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
        }

        //新的协会总规格id
        String newSampleId = materialsSpecConfig.getSampleId();

        if (newSampleId == null) {
            log.error("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
            throw new RuntimeException("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
        }
        log.info("修改后的SampleID: {}", newSampleId);


        if (newSampleId.equals(oldSampleID)) {
            log.info("修改的原材料规格与现材料规格一致，无需修改");
            return;
        }


        for (String str : set) {
            //如果为细骨料 且为天然砂  定死值 含泥量为 110312108
            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType()) && str.equals("含泥量")) {
                continue;
            } else {
                Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, oldSampleID);

                if (itemParameter == null) {
                    log.error("修改物料规格是未查询到对应的材料：value = " + str + "oldSampleID =" + oldSampleID);
                    continue;
                }
                String oldParameterID = itemParameter.get("ParameterID").toString();

                //查询data_defalutUc 是否存在
                Map<String, Object> defaultUCBySampleNo = dataDefUcLaboratoryMapper.findDATA_DefaultUCBySampleNo(sampleNo, oldParameterID);
                if (defaultUCBySampleNo != null) {
                    Map<String, Object> newItemParameter = m_uploadLaboratoryMapper.findItemParameter(str, oldSampleID);

                    if (newItemParameter == null) {
                        log.error("修改物料规格是未查询到对应的材料：value = " + str + "newSampleID =" + oldSampleID);
                        continue;
                    }

                    String newParameterID = newItemParameter.get("ParameterID").toString();

                    DataDefaultUc defaultUc = new DataDefaultUc();
                    defaultUc.setSampleNo(sampleNo)
                            .setUcParameterID(oldParameterID)
                            .setNewUcParameterID(newParameterID)
                            .setUploadFlag(defaultUCBySampleNo.get("Upload_Flag").toString());
                    dataDefUcLaboratoryMapper.updateDATA_DefaultUC(defaultUc);
                }

            }

        }
        log.info("修改协会物料DATA_DefaultUC表结束。。。");

    }


    @Override
    public void updateRepresentativeQuantity(Integer ITID, Float scQuantity) {
        log.info("更新委托代表数量开始，小票号：【{}】，混凝土生产方量：【{}】", ITID, scQuantity);

        if (ITID == null || scQuantity == null) {
            return;
        }

        try {

            //查询小票对应的委托信息
            ExperimentItemorder itemorder = new ExperimentItemorder().setItemorderId(ITID);
            List<ExperimentItemorder> list = experimentItemorderMapper.getList(itemorder);

            if (list.size() != 0 && !list.isEmpty()) {
                ExperimentItemorder item = list.get(0);

                //更新品控台账的代表数量
                Experiment experiment = new Experiment().setId(item.getExperimentId()).setBehalfNumber(Double.valueOf(scQuantity));
                experimentMapper.updateByPrimaryKeySelective(experiment);

                //查询与协会的委托关系
                List<ShxhSynchronizedata> mapperList = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setExperimentId(experiment.getId()));
                if (mapperList != null && !mapperList.isEmpty()) {
                    ShxhSynchronizedata synchronizedata = mapperList.get(0);

                    if (StringUtils.isNotBlank(synchronizedata.getConsignId()) && StringUtils.isNotBlank(synchronizedata.getSampleId())) {
                        WtSample wtSample = new WtSample();
                        wtSample.setSampleNo(synchronizedata.getSampleId());
                        wtSample.setDelegateQuan(String.valueOf(scQuantity));
                        wtSampleMapper.updateWtSample(wtSample);
                    }
                }
            } else {
                log.info("未查询到小票对应的委托信息，小票号：【{}】，混凝土生产方量：【{}】", ITID, scQuantity);
            }
        } catch (Exception e) {
            log.error("更新委托代表数量操作失败 ：" + e.getMessage(), e);
            throw new RuntimeException("更新委托代表数量操作失败" + e.getMessage());
        }


    }


    //新增试验台账信息
    private String addTestLedger(Experiment experiment, String sampleNo, ImportList importList) {

        //查询物料价格
        SupplierCompanyMaterials supplierCompanyMaterials = new SupplierCompanyMaterials();
        if (experiment.getMaterialsId() != null && !experiment.getMaterialsId().isEmpty()) {
            List<SupplierCompanyMaterials> list = supplierCompanyMaterialsMapper.getList(new SupplierCompanyMaterials().setMaterialsId(Long.parseLong(experiment.getMaterialsId())));
            if (list != null && list.size() != 0) {
                supplierCompanyMaterials = list.get(0);
            }

        }


        //根据台账 查询品控做的试验项目详情
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));
        //查询出品控的水泥试验项目配置
        List<TestProjectInfo> testProjectInfoList = new ArrayList<>();
        //存储协会需要做的项目集合
        Set<String> set = new LinkedHashSet<>();

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            //查询出品控的水泥试验项目配置
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CEMENT.getTestProjectType()));
        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FLY.getTestProjectType()));
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.SLAG.getTestProjectType()));
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.COARSE.getTestProjectType()));
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FINE.getTestProjectType()));
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.ADMIXTURE.getTestProjectType()));
        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CONCRETE.getTestProjectType()));
        }


        for (ExperimentDetail detail : list) {

            //判断试验项目中平均值是否为空
            if (!isOrNull(detail, experiment)) {
                continue;
            }
            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                    if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {

                        //细骨料含泥量 特殊处理   含泥量默认对应三条协会试验  如果为天然砂 则直接取第一条  如果是机制砂则取第二第三条
                        if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode())) {

                            String[] split = testProjectInfo.getParameterName().split(",");

                            //机制砂
                            if (experiment.getMaterialsName() != null && ("机制砂".equals(experiment.getMaterialsName()) || "混合砂".equals(experiment.getMaterialsName()) || "人工砂".equals(experiment.getMaterialsName()))) {
                                // 确保至少有 2 个元素
                                if (split.length > 1) {
                                    set.add(split[1]);
                                }
                                // 确保至少有 3 个元素
                                if (split.length > 2) {
                                    set.add(split[2]);
                                }
                                // 确保至少有 4 个元素，才能访问 split[3]
                                if (split.length > 3) {
                                    set.add(split[3]);
                                }
                                if (split.length > 4) {
                                    set.add(split[4]);
                                }
                                //天然砂
                            } else {
                                if (split.length > 0) {
                                    set.add(split[0]);
                                }
                            }
                        } else {
                            //添加进协会需要做的项目集合
                            set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                        }
                    }
                }
            }

        }

        //如果所有项目都没做 则不生成协会台账信息
        if (set.isEmpty()) {
            return null;
        }
        String SampleID = importList.getSampleID();
/*        String examParameter = "";
        String examParameterCn = "";
        String status = "";
        //根据原材料名称查找原材料项目
        //查出所有试验项目


        for (String str : set) {

            //如果为细骨料 且为天然砂  定死值 含泥量为 110312108
            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType()) && str.equals("含泥量")) {
                examParameter += "110312108" + ";";
                examParameterCn += str + ";";

                // （0,待检，1已检，2在检）    这里由于品控是保存抽样动作 就是试验中  所以协会直接改成 在检
                status += "0" + ";";
            } else {
                Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, SampleID);

                if (itemParameter == null) {
                    log.error("未查询到对应的材料：value = " + str + "SampleID =" + SampleID);
                    continue;
                }

                examParameter += itemParameter.get("ParameterID").toString() + ";";
                examParameterCn += str + ";";

                // （0,待检，1已检，2在检）    这里由于品控是保存抽样动作 就是试验中  所以协会直接改成 在检
                status += "0" + ";";
            }

        }*/

        // 将 set 转为 List 并排序（按 ParameterID）
        List<Map<String, Object>> parameterList = new ArrayList<>();

        for (String str : set) {
            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType()) && str.equals("含泥量")) {
                // 特殊处理：含泥量固定为 110312108
                Map<String, Object> item = new HashMap<>();
                item.put("ParameterID", "110312108");
                item.put("ParameterName", "含泥量");
                parameterList.add(item);
            } else {
                Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, SampleID);
                if (itemParameter != null) {
                    parameterList.add(itemParameter);
                }
            }
        }

        // 按 ParameterID 排序（升序）
        parameterList.sort((a, b) -> {
            String id1 = a.get("ParameterID").toString();
            String id2 = b.get("ParameterID").toString();
            return Integer.compare(Integer.parseInt(id1), Integer.parseInt(id2));
        });

        // 再次拼接 examParameter 和 examParameterCn
        StringBuilder examParameter = new StringBuilder();
        StringBuilder examParameterCn = new StringBuilder();
        StringBuilder status = new StringBuilder();

        for (Map<String, Object> item : parameterList) {
            examParameter.append(item.get("ParameterID")).append(";");
            examParameterCn.append(item.get("ParameterName")).append(";");
            status.append("0").append(";");
        }


        //代表数量
        Double behalfNumber = experiment.getRealMaterialNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }
        //生成对应的  uploadFlag
        String wSUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), null);

        //委托编号
        String consign = generateConsingId(experiment, list);

        WtSample wS = new WtSample();
        wS.setSampleNo(sampleNo);
        wS.setConSignId(consign);
        wS.setExamParameter(examParameter.toString());
        wS.setExamParameterCn(examParameterCn.toString());
        wS.setKindId(importList.getKindId());
        wS.setItemId(importList.getItemId());
        wS.setSampleId(SampleID);
        wS.setSpecId(importList.getSpecId());
        wS.setGradeId(importList.getGradeId());
        wS.setStatus(status.toString());
        wS.setSampleStatus("2");  // （0,待检，1已检，2在检）    这里由于品控是保存抽样动作 就是试验中  所以协会直接改成 在检
        wS.setSampleModify("0");
        wS.setSampleRegular("1");
        wS.setDelegateQuan(behalfNumber == null ? "0" : String.valueOf(behalfNumber));
        wS.setDelegateQuanUnit(importList.getProdinUnit());
        wS.setProduceFactory(importList.getFactoryName());
        wS.setExamResult(experiment.getConclusion());
        if (supplierCompanyMaterials.getUnitPrice() != null) {
            wS.setPrince(supplierCompanyMaterials.getUnitPrice().toString());//单价
        }
        wS.setRecordCertificate(importList.getRecordCertificate());

        //wS.setMoldingDate(new Date());

        wS.setImportId(importList.getImportId() + ";");

        wS.setUploadFlag(wSUploadFlag);

        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            wS.setIsProduce("1"); //是否生产任务(0为原材料,1为生产任务)
        } else {
            wS.setIsProduce("0"); //是否生产任务(0为原材料,1为生产任务)
        }

        log.info("新增协会WtSample数据{}", wS);
        //新增WtSample 信息
        wtSampleMapper.insertWtSample(wS);


        String wcUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), "0001-01-01");
        String newId = keyPropertyMapper.getNewId();


        WtConsign wC = new WtConsign();
        wC.setId(newId);
        wC.setConSignId(consign);
        wC.setSampleNo(sampleNo);
        wC.setKindId(importList.getKindId());
        wC.setItemId(importList.getItemId());

        /*SimpleDateFormat sdf = new SimpleDateFormat(DateHelper.getDefaultDateTimeFormat());
        String formattedDate = sdf.format(new Date());
        Date date = DateHelper.parseDateTime(DateHelper.getDefaultDateFormat(), DateHelper.getDefaultLocal(), formattedDate);*/

        wC.setSamplingDate(experiment.getEntrustTime());

        wC.setProjectId("1");
        wC.setWitnessNo("11");
        wC.setSamplingNo("11");
        wC.setProjectName("JBZ");
        wC.setUploadFlag(wcUploadFlag);
        wC.setExamConclusion(experiment.getConclusion());
        wC.setExamKind("取样");
        wC.setExamQuan("1");
        wC.setGetreportType("自取");
        wC.setProjectSsn("1");
        wC.setMemo(experiment.getRemark());

        if (supplierCompanyMaterials.getUnitPrice() != null) {
            wC.setTotalPrices(supplierCompanyMaterials.getUnitPrice().toString());//总价
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(experiment.getEntrustTime());
        try {
            Date dateToStore = sdf.parse(dateString);
            wC.setDeliverDate(dateToStore);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        //新增WtConsign 信息
        wtConsignMapper.insertWtConsign(wC);


        //当前年份后两位值
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearLastTwoDigits = String.valueOf(year).substring(2, 4);

        String itemID = importList.getItemId();

        WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemID);
        String sampleNoSubstring = String.valueOf(Long.parseLong(sampleNo) + 1).substring(4);
        String consignNoSubstring = String.valueOf(Long.parseLong(consign) + 1).substring(4);
        if (wtCurrentNewId == null) {
            //新增
            WtCurrentNew wtCurrentNew = new WtCurrentNew().setYearStr(yearLastTwoDigits).setItemId(itemID).setCurrentConsignId(consignNoSubstring).setCurrentSampleId(sampleNoSubstring);
            wtCurrentIdMapper.addWtCurrentIdNew(wtCurrentNew);
        } else {
            //修改
            WtCurrentNew wtCurrentNew = new WtCurrentNew().setYearStr(yearLastTwoDigits).setItemId(itemID).setCurrentConsignId(consignNoSubstring).setCurrentSampleId(sampleNoSubstring);
            wtCurrentIdMapper.updateWtCurrentNewId(wtCurrentNew);
        }

        log.info("同步新增原材料委托结束，协会委托编号：【{}】，样品编号；【{}】", wC.getConSignId(), wC.getSampleNo());

        return wC.getConSignId();
    }

    //修改原材料试验台账信息
    private void updateTestLedger(Experiment experiment, String sampleNo, ImportList importList, String consignId) {

        //查询物料价格
        SupplierCompanyMaterials supplierCompanyMaterials = new SupplierCompanyMaterials();
        if (experiment.getMaterialsId() != null && !experiment.getMaterialsId().isEmpty()) {
            List<SupplierCompanyMaterials> list = supplierCompanyMaterialsMapper.getList(new SupplierCompanyMaterials().setMaterialsId(Long.parseLong(experiment.getMaterialsId())));
            if (list != null && !list.isEmpty()) {
                supplierCompanyMaterials = list.get(0);
            }

        }

        //根据台账 查询品控做的试验项目详情
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));
        //查询出品控的水泥试验项目配置
        List<TestProjectInfo> testProjectInfoList = new ArrayList<>();
        //存储协会需要做的项目集合
        Set<String> set = new LinkedHashSet<>();

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            //查询出品控的水泥试验项目配置
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CEMENT.getTestProjectType()));
        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FLY.getTestProjectType()));
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.SLAG.getTestProjectType()));
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.COARSE.getTestProjectType()));
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.FINE.getTestProjectType()));
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.ADMIXTURE.getTestProjectType()));
        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CONCRETE.getTestProjectType()));
        }


        for (ExperimentDetail detail : list) {

            //判断试验项目中平均值是否为空
            if (!isOrNull(detail, experiment)) {
                continue;
            }
            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                if (StringUtils.isBlank(detail.getTestProjectCode()) || StringUtils.isBlank(testProjectInfo.getTestCode())) {
                    continue;
                }
                if (testProjectInfo.getTestCode().equals(detail.getTestProjectCode()) && StringUtils.isNotBlank(testProjectInfo.getParameterName())) {

                    //细骨料含泥量 特殊处理   含泥量默认对应三条协会试验  如果为天然砂 则直接取第一条  如果是机制砂则取第二第三条
                    if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode())) {

                        String[] split = testProjectInfo.getParameterName().split(",");

                        //机制砂
                        if (experiment.getMaterialsName() != null && ("机制砂".equals(experiment.getMaterialsName()) || "混合砂".equals(experiment.getMaterialsName()) || "人工砂".equals(experiment.getMaterialsName()))) {
                            // 确保至少有 2 个元素
                            if (split.length > 1) {
                                set.add(split[1]);
                            }
                            // 确保至少有 3 个元素
                            if (split.length > 2) {
                                set.add(split[2]);
                            }
                            // 确保至少有 4 个元素，才能访问 split[3]
                            if (split.length > 3) {
                                set.add(split[3]);
                            }
                            if (split.length > 4) {
                                set.add(split[4]);
                            }
                            //天然砂
                        } else {
                            if (split.length > 0) {
                                set.add(split[0]);
                            }
                        }
                    } else {
                        //添加进协会需要做的项目集合
                        set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                    }
                }
            }

        }

        //如果所有项目都没做 则不生成协会台账信息
        if (set == null || set.size() == 0) {
            return;
        }
        String SampleID = importList.getSampleID();
        //根据原材料名称查找原材料项目
        //查出所有试验项目

        Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);
        if (wtSampleList == null) {
            log.info("修改原材料委托时出现错误，未查询到协会样品数据，样品id:", sampleNo);
            return;
        }


        // 获取并处理原始数据
        String examParameterCn = Optional.ofNullable(wtSampleList.get("Exam_parameter_Cn")).map(Object::toString).orElse("");
        String examParameter = Optional.ofNullable(wtSampleList.get("Exam_Parameter")).map(Object::toString).orElse("");
        String status = Optional.ofNullable(wtSampleList.get("Status")).map(Object::toString).orElse("");

        // 去除末尾分号并分割
        String[] codeArray = examParameter.split("(;|$)");
        String[] nameArray = examParameterCn.split("(;|$)");
        String[] statusArray = status.split("(;|$)");

        // 构建原始参数列表（保留原始顺序）
        List<Map<String, Object>> originalList = new ArrayList<>();
        for (int i = 0; i < nameArray.length && i < codeArray.length && i < statusArray.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("ParameterID", codeArray[i]);
            item.put("ParameterName", nameArray[i]);
            item.put("Status", statusArray[i]);
            originalList.add(item);
        }

        List<Map<String, Object>> newList = new ArrayList<>();

        for (String str : set) {
            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType()) && "含泥量".equals(str)) {
                // 特殊处理：含泥量固定为 110312108
                Map<String, Object> item = new HashMap<>();
                item.put("ParameterID", "110312108");
                item.put("ParameterName", "含泥量");
                item.put("Status", "0"); // 默认状态
                newList.add(item);
            } else {
                Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, SampleID);
                if (itemParameter == null) {
                    log.error("未查询到对应的材料：value = {} SampleID = {}", str, SampleID);
                    continue;
                }
                Map<String, Object> item = new HashMap<>();
                item.put("ParameterID", itemParameter.get("ParameterID"));
                item.put("ParameterName", str);
                item.put("Status", "0"); // 新增默认状态为“待检”
                newList.add(item);
            }
        }


        // 合并两个列表
        List<Map<String, Object>> combinedList = new ArrayList<>(originalList);
        combinedList.addAll(newList);


        // 按 ParameterID 升序排序（推荐）
        combinedList.sort((a, b) -> {
            String id1 = a.get("ParameterID").toString();
            String id2 = b.get("ParameterID").toString();
            return Integer.compare(Integer.parseInt(id1), Integer.parseInt(id2));
        });

        //去重
        Set<String> seenNames = new HashSet<>();
        List<Map<String, Object>> deduped = new ArrayList<>();

        for (Map<String, Object> item : combinedList) {
            String name = item.get("ParameterName").toString();
            if (!seenNames.contains(name)) {
                seenNames.add(name);
                deduped.add(item);
            }
        }

        StringBuilder examParameterNew = new StringBuilder();
        StringBuilder examParameterCnNew = new StringBuilder();
        StringBuilder statusNew = new StringBuilder();

        for (Map<String, Object> item : deduped) {
            examParameterNew.append(item.get("ParameterID")).append(";");
            examParameterCnNew.append(item.get("ParameterName")).append(";");
            statusNew.append(item.get("Status")).append(";");
        }

       /*    // 构建名称 -> 状态映射
        Map<String, String> nameToStatus = new HashMap<>();
        for (int i = 0; i < nameArray.length && i < statusArray.length; i++) {
            nameToStatus.put(nameArray[i], statusArray[i]);
        }

        // 构建结果
        StringBuilder examParameterNew = new StringBuilder();
        StringBuilder examParameterCnNew = new StringBuilder();
        StringBuilder statusNew = new StringBuilder();

        for (String str : set) {
            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType()) && "含泥量".equals(str)) {
                // 特殊情况处理  //如果为细骨料 且为天然砂  定死值 含泥量为 110312108
                examParameterNew.append("110312108;");
                examParameterCnNew.append("含泥量;");
            } else {
                Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, SampleID);
                if (itemParameter == null) {
                    log.error("未查询到对应的材料：value = {} SampleID = {}", str, SampleID);
                    continue;
                }
                examParameterNew.append(itemParameter.get("ParameterID")).append(";");
                examParameterCnNew.append(str).append(";");
            }

            // 统一处理状态
            String matchedStatus = nameToStatus.getOrDefault(str, "0");
            statusNew.append(matchedStatus).append(";");
        }*/

        //代表数量
        Double behalfNumber = experiment.getRealMaterialNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }

        WtSample wS = new WtSample();
        wS.setSampleNo(sampleNo);
        wS.setExamParameter(examParameterNew.toString());
        wS.setExamParameterCn(examParameterCnNew.toString());
        wS.setStatus(statusNew.toString());

        wS.setDelegateQuan(behalfNumber == null ? "0" : String.valueOf(behalfNumber));

        wS.setDelegateQuanUnit(importList.getProdinUnit());
        wS.setProduceFactory(importList.getFactoryName());
        if (supplierCompanyMaterials.getUnitPrice() != null) {
            wS.setPrince(supplierCompanyMaterials.getUnitPrice().toString());//单价
        }

        wS.setExamResult(experiment.getConclusion());

        wS.setGradeId(importList.getGradeId());
        wS.setSpecId(importList.getSpecId());
        wS.setSampleId(importList.getSampleID());

        //修改WtSample 信息
        wtSampleMapper.updateWtSample(wS);


        WtConsign wC = new WtConsign();
        wC.setConSignId(consignId);
        wC.setExamConclusion(experiment.getConclusion());
        wC.setMemo(experiment.getRemark());
        wC.setSamplingDate(experiment.getEntrustTime());
        if (supplierCompanyMaterials.getUnitPrice() != null) {
            wC.setTotalPrices(supplierCompanyMaterials.getUnitPrice().toString());//总价
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(experiment.getEntrustTime());
        try {
            Date dateToStore = sdf.parse(dateString);
            wC.setDeliverDate(dateToStore);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

        //新增WtConsign 信息
        wtConsignMapper.updateWtConsignNew(wC);

        log.info("同步修改原材料委托结束，协会委托编号：【{}】，样品编号；【{}】", consignId, sampleNo);
    }

    private boolean isOrNull(ExperimentDetail detail, Experiment experiment) {

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            return cement(detail);
        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            return fly(detail);
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            return slag(detail);
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            return coarse(detail);
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            return fine(detail);
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            return admixture(detail);
        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            return concrete(detail);
        }

        return false;
    }

    //混凝土
    private boolean concrete(ExperimentDetail detail) {
        JSONObject objJson = detail.getObjJson();

        //抗压强度
        if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
            return true;
          /*  ConcreteKyqd concreteKyqd = objJson.toJavaObject(ConcreteKyqd.class);
            if (concreteKyqd != null  && StringUtils.isNotBlank(concreteKyqd.getPjz7d()) && StringUtils.isNotBlank(concreteKyqd.getPjz28d())) {
                return true;
            }*/
            //抗渗等级
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode())) {
        /*    ConcreteKsdj concreteKsdj = objJson.toJavaObject(ConcreteKsdj.class);
            if (concreteKsdj != null  && StringUtils.isNotBlank(concreteKsdj.getSsksdj())
                    && (concreteKsdj.getSsksdj().contains("P6") || concreteKsdj.getSsksdj().contains("P8") || concreteKsdj.getSsksdj().contains("P10") || concreteKsdj.getSsksdj().contains("P12"))) {
                return true;
            }*/
        }

        return false;
    }

    //外加剂
    private boolean admixture(ExperimentDetail detail) {
        JSONObject objJson = detail.getObjJson();

        //PH值
        if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_PHZ.getCode())) {
            return true;
            //将json转成对象
         /*   ConcreteAdmixturePhz concreteAdmixturePhz = objJson.toJavaObject(ConcreteAdmixturePhz.class);
            if (concreteAdmixturePhz != null && StringUtils.isNotBlank(concreteAdmixturePhz.getPjph())) {
                return true;
            }*/
            //密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_MD.getCode())) {
            return true;
            //将json转成对象
         /*   ConcreteAdmixtureMd concreteAdmixtureMd = objJson.toJavaObject(ConcreteAdmixtureMd.class);
            if (concreteAdmixtureMd != null && concreteAdmixtureMd.getJmmdInfo() != null && StringUtils.isNotBlank(concreteAdmixtureMd.getJmmdInfo().getMdpjz())) {
                return true;
            }*/
            //含固量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_HGL.getCode())) {
            return true;
            //将json转成对象
         /*   ConcreteAdmixtureHgl concreteAdmixtureHgl = objJson.toJavaObject(ConcreteAdmixtureHgl.class);
            if (concreteAdmixtureHgl != null && StringUtils.isNotBlank(concreteAdmixtureHgl.getPjhgl())) {
                return true;
            }*/
            //凝结时间之差
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_NJSJZC.getCode())) {
            //将json转成对象
            ConcreteAdmixtureNjsjzc concreteAdmixtureNjsjzc = objJson.toJavaObject(ConcreteAdmixtureNjsjzc.class);
            if (concreteAdmixtureNjsjzc != null && StringUtils.isNotBlank(concreteAdmixtureNjsjzc.getCnsjzc()) && StringUtils.isNotBlank(concreteAdmixtureNjsjzc.getZnsjzc())) {
                return true;
            }
            //泌水率比
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_QSLB.getCode())) {
            //将json转成对象
            ConcreteAdmixtureQslb concreteAdmixtureQslb = objJson.toJavaObject(ConcreteAdmixtureQslb.class);
            if (concreteAdmixtureQslb != null && StringUtils.isNotBlank(concreteAdmixtureQslb.getQslb())) {
                return true;
            }
            //减水率
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_JSL.getCode())) {
            //将json转成对象
            ConcreteAdmixtureJSL concreteAdmixtureJSL = objJson.toJavaObject(ConcreteAdmixtureJSL.class);
            if (concreteAdmixtureJSL != null && StringUtils.isNotBlank(concreteAdmixtureJSL.getPjz())) {
                return true;
            }
            //塌落度1h经时变化量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_ADMIXTURE_PARAM_WJJ_TLD1HJSBHL.getCode())) {
            //将json转成对象
            ConcreteAdmixtureTld1hjsbhl concreteAdmixtureTld1hjsbhl = objJson.toJavaObject(ConcreteAdmixtureTld1hjsbhl.class);
            if (concreteAdmixtureTld1hjsbhl != null && concreteAdmixtureTld1hjsbhl.getSjhntObject() != null
                    && StringUtils.isNotBlank(concreteAdmixtureTld1hjsbhl.getSjhntObject().getH1bhlpjz())) {
                return true;
            }
        }


        return false;
    }

    //细骨料
    private boolean fine(ExperimentDetail detail) {
        JSONObject objJson = detail.getObjJson();
        //含泥量
        if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode())) {
            return true;
            //将json转成对象
   /*         FineAggregateHnl fineNnl = objJson.toJavaObject(FineAggregateHnl.class);
            if (fineNnl != null && StringUtils.isNotBlank(fineNnl.getHnlpjz())) {
                return true;
            }*/

            //含水率
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HSL.getCode())) {
            FineAggregateHsl fineHsl = objJson.toJavaObject(FineAggregateHsl.class);
            if (fineHsl != null && StringUtils.isNotBlank(fineHsl.getPjz())) {
                return true;
            }
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_YSZZB.getCode())) {
            //将json转成对象
            FineAggregateYszzb fineYszzb = objJson.toJavaObject(FineAggregateYszzb.class);
            if (fineYszzb != null && StringUtils.isNotBlank(fineYszzb.getZyszb())) {
                return true;
            }
            //表观密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_BGMD.getCode())) {
            //将json转成对象
            FineAggregateBgmd fineBgmd = objJson.toJavaObject(FineAggregateBgmd.class);
            if (fineBgmd != null && StringUtils.isNotBlank(fineBgmd.getPjz())) {
                return true;
            }
            //堆积密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_DJMD.getCode())) {
            //将json转成对象
            FineAggregateDjmd fineDjmd = objJson.toJavaObject(FineAggregateDjmd.class);
            if (fineDjmd != null && StringUtils.isNotBlank(fineDjmd.getPjz())) {
                return true;
            }
            //紧密密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_JMMD.getCode())) {
            //将json转成对象
            FineAggregateJmmd fineJmmd = objJson.toJavaObject(FineAggregateJmmd.class);
            if (fineJmmd != null && StringUtils.isNotBlank(fineJmmd.getPjz())) {
                return true;
            }
            //筛分析
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_SFX.getCode())) {
            return true;
            //将json转成对象
          /*  FineAggregateSfx fineSfx = objJson.toJavaObject(FineAggregateSfx.class);
            if (fineSfx != null && StringUtils.isNotBlank(fineSfx.getXdmspjz())) {

            }*/
            //泥块含量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_NKHL.getCode())) {
            return true;
            //将json转成对象
      /*      FineAggregateNkhl fineNkhl = objJson.toJavaObject(FineAggregateNkhl.class);
            if (fineNkhl != null && StringUtils.isNotBlank(fineNkhl.getPjz())) {
                return true;
            }*/
            //氯离子含量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_LLZHL.getCode())) {
            return true;
            //将json转成对象
           /* FineAggregateLlzhl llzhl = objJson.toJavaObject(FineAggregateLlzhl.class);
            if (llzhl != null && StringUtils.isNotBlank(llzhl.getPjz())) {
                return true;
            }*/
            //胶砂流动度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_JSLDD.getCode())) {
            FineAggregateJsldd fineJsldd = objJson.toJavaObject(FineAggregateJsldd.class);
            if (fineJsldd != null && StringUtils.isNotBlank(fineJsldd.getDxjl())) {
                return true;
            }
        }


        return false;
    }

    //粗骨料
    private boolean coarse(ExperimentDetail detail) {
        JSONObject objJson = detail.getObjJson();
        //含泥量
        if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_HNL.getCode())) {
            return true;
            //将json转成对象
        /*    CoarseAggregateHnl coarseHnl = objJson.toJavaObject(CoarseAggregateHnl.class);
            if (coarseHnl != null && StringUtils.isNotBlank(coarseHnl.getHnlpjz())) {
                return true;
            }*/
            //含泥块量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_HNKL.getCode())) {
            return true;
            //将json转成对象
         /*   CoarseAggregateHnkl coarseHnkl = objJson.toJavaObject(CoarseAggregateHnkl.class);
            if (coarseHnkl != null && StringUtils.isNotBlank(coarseHnkl.getHnlpjz())) {
                return true;
            }*/
            //针、片状颗粒含量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_ZPZKLHL.getCode())) {
            return true;
            //将json转成对象
     /*       CoarseAggregateZpzklhl coarseZpzklhl = objJson.toJavaObject(CoarseAggregateZpzklhl.class);
            if (coarseZpzklhl != null && StringUtils.isNotBlank(coarseZpzklhl.getZpzkklhl())) {
                return true;
            }*/
            //筛分析
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_SFX.getCode())) {
            return true;
            //将json转成对象
        /*    CoarseAggregateSfx coarseSfx = objJson.toJavaObject(CoarseAggregateSfx.class);
            if (coarseSfx != null && StringUtils.isNotBlank(coarseSfx.getDxjl())) {
                return true;
            }*/
            //压碎值指标
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_YSZZB.getCode())) {
            //将json转成对象
            CoarseAggregateYszzb coarseYszzb = objJson.toJavaObject(CoarseAggregateYszzb.class);
            if (coarseYszzb != null && StringUtils.isNotBlank(coarseYszzb.getPjz())) {
                return true;
            }
            //表观密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_BGMD.getCode())) {
            //将json转成对象
            CoarseAggregateBgmd coarseBgmd = objJson.toJavaObject(CoarseAggregateBgmd.class);
            if (coarseBgmd != null && StringUtils.isNotBlank(coarseBgmd.getPjz())) {
                return true;
            }
            //堆积密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_DJMD.getCode())) {
            //将json转成对象
            CoarseAggregateDjmd coarseDjmd = objJson.toJavaObject(CoarseAggregateDjmd.class);
            if (coarseDjmd != null && StringUtils.isNotBlank(coarseDjmd.getPjz())) {
                return true;
            }
            //紧密密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_JMMD.getCode())) {
            //将json转成对象
            CoarseAggregateJmmd coarseJmmd = objJson.toJavaObject(CoarseAggregateJmmd.class);
            if (coarseJmmd != null && StringUtils.isNotBlank(coarseJmmd.getPjz())) {
                return true;
            }
        }

        return false;
    }

    //水泥
    private boolean cement(ExperimentDetail detail) {
        JSONObject objJson = detail.getObjJson();
        //安定性
        if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_ADX.getCode())) {
            return true;
            //将json转成对象
            /*CementAdx cementAdx = objJson.toJavaObject(CementAdx.class);
            if (cementAdx != null && cementAdx.getSbf() != null && StringUtils.isNotBlank(cementAdx.getSbf().getJl())) {
                return true;
            }*/
            //水泥标准稠度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_BZCD.getCode())) {
            return true;
            //将json转成对象
           /* CementBzcd cementBzcd = objJson.toJavaObject(CementBzcd.class);
            if (cementBzcd != null && StringUtils.isNotBlank(cementBzcd.getBzcdysl())) {
                return true;
            }*/
            //水泥凝结时间
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_NJSJ.getCode())) {
            return true;
            //将json转成对象
      /*      CementNjsj cementNjsj = JsonUtils.getObject(objJson, CementNjsj.class);
            if (cementNjsj != null && cementNjsj.getJgjs() != null && StringUtils.isNotBlank(cementNjsj.getJgjs().getCnsj()) && StringUtils.isNotBlank(cementNjsj.getJgjs().getZnsj())) {
                return true;
            }*/
            //水泥强度测定
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_QDCD.getCode())) {
            return true;
            //水泥的强度测定要强制默认必须上传（因为强度测定是要在协会里面输入，自动同步过来，本地不会填）
          /*  //将json转成对象
            CementQdcd cementQdcd = JsonUtils.getObject(objJson, CementQdcd.class);
            //水泥的强度测定要强制默认必须上传（因为强度测定是要在协会里面输入，自动同步过来，本地不会填）
            return true;
           /* if (cementQdcd != null && cementQdcd.getKzqdsy28d() != null && StringUtils.isNotBlank(cementQdcd.getKzqdsy28d().getPjz())) {
                return true;
            }*/
            //水泥细度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_XD.getCode())) {
            //将json转成对象
            CementXd cementXd = JsonUtils.getObject(objJson, CementXd.class);
            if (cementXd != null && StringUtils.isNotBlank(cementXd.getPjz())) {
                return true;
            }
            //水泥密度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_MD.getCode())) {
            //将json转成对象
            CementMd cementMd = JsonUtils.getObject(objJson, CementMd.class);
            if (cementMd != null && StringUtils.isNotBlank(cementMd.getPjz())) {
                return true;
            }
            //比表面积
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_BBMJ.getCode())) {
            //将json转成对象
            CementBbmj cementBbmj = objJson.toJavaObject(CementBbmj.class);
            if (cementBbmj != null && StringUtils.isNotBlank(cementBbmj.getPjz())) {
                return true;
            }
        }

        return false;
    }

    //矿渣粉
    private boolean slag(ExperimentDetail detail) {
        //品控试验json
        JSONObject objJson = detail.getObjJson();
        //密度
        if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_YPMD.getCode())) {
            //将json转成对象
            SlagYpmd slagYpmd = objJson.toJavaObject(SlagYpmd.class);
            if (slagYpmd != null && StringUtils.isNotBlank(slagYpmd.getPjz())) {
                return true;
            }
            //烧失量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_SSL.getCode())) {
            //将json转成对象
            SlagSsl slagSsl = objJson.toJavaObject(SlagSsl.class);
            if (slagSsl != null && StringUtils.isNotBlank(slagSsl.getSslpjz())) {
                return true;
            }
            //流动度比
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_LDDB.getCode())) {
            return true;
            //将json转成对象
        /*    SlagLddb slagLddb = objJson.toJavaObject(SlagLddb.class);
            if (slagLddb != null && StringUtils.isNotBlank(slagLddb.getSyjg())) {
                return true;
            }*/
            //含水率
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_HSL.getCode())) {
            //将json转成对象
            SlagHsl slagHsl = objJson.toJavaObject(SlagHsl.class);
            if (slagHsl != null && StringUtils.isNotBlank(slagHsl.getHsl())) {
                return true;
            }
            //活性指数
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_HXZS.getCode())) {
            return true;
            //将json转成对象
           /* SlagHdzs slagHdzs = objJson.toJavaObject(SlagHdzs.class);
            if (slagHdzs != null && slagHdzs.getHxzsInfoList().size() > 1 && StringUtils.isNotBlank(slagHdzs.getHxzsInfoList().get(1).getHxzs())) {
                return true;
            }*/
            //比表面积
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_BBMJ.getCode())) {
            //将json转成对象
            SlagBbmj slagBbmj = objJson.toJavaObject(SlagBbmj.class);
            if (slagBbmj != null && StringUtils.isNotBlank(slagBbmj.getPjz())) {
                return true;
            }
        }


        return false;
    }

    //粉煤灰
    private boolean fly(ExperimentDetail detail) {
        //品控试验json
        JSONObject objJson = detail.getObjJson();
        //安定性
        if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_ADX.getCode())) {
            return true;
            //将json转成对象
         /*   FlyAskAdx flyAskAdx = objJson.toJavaObject(FlyAskAdx.class);
            if (flyAskAdx != null && flyAskAdx.getLsf() != null && StringUtils.isNotBlank(flyAskAdx.getLsf().getPjz())) {
                return true;
            }*/
            //含水量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_HSL.getCode())) {
            return true;
            //将json转成对象
        /*    FlyAskHsl flyAskHsl = objJson.toJavaObject(FlyAskHsl.class);
            if (flyAskHsl != null && StringUtils.isNotBlank(flyAskHsl.getHsl())) {
                return true;
            }*/
            //细度
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_XD.getCode())) {
            return true;
            //将json转成对象
          /*  FlyAskXd flyAskXd = objJson.toJavaObject(FlyAskXd.class);
            if (flyAskXd != null && StringUtils.isNotBlank(flyAskXd.getJzhxddbz())) {
                return true;
            }*/
            //需水量比
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_XSLB.getCode())) {
            return true;
            //将json转成对象
         /*   FlyAskXslb flyAskXslb = objJson.toJavaObject(FlyAskXslb.class);
            if (flyAskXslb != null && StringUtils.isNotBlank(flyAskXslb.getXslb())) {
                return true;
            }*/
            //三氧化硫
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_SYHL.getCode())) {
            //将json转成对象
            FlyAskSyhl flyAskSyhl = objJson.toJavaObject(FlyAskSyhl.class);
            if (flyAskSyhl != null && StringUtils.isNotBlank(flyAskSyhl.getPjz())) {
                return true;
            }
            //游离氧化钙
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_YLYHG.getCode())) {
            //将json转成对象
            FlyAskYlyhg flyAskYlyhg = objJson.toJavaObject(FlyAskYlyhg.class);
            if (flyAskYlyhg != null && StringUtils.isNotBlank(flyAskYlyhg.getPjz())) {
                return true;
            }
            //烧失量
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_SSL.getCode())) {
            return true;
            //将json转成对象
         /*   FlyAskSsl flyAskSsl = objJson.toJavaObject(FlyAskSsl.class);
            if (flyAskSsl != null && StringUtils.isNotBlank(flyAskSsl.getSslpjz())) {
                return true;
            }*/
            //活性指数
        } else if (detail.getTestProjectCode().equals(TestProjectEnum.FLY_ASK_PARAM_FMH_HXZS.getCode())) {
            //将json转成对象
            FlyAskHdzs flyAskHdzs = objJson.toJavaObject(FlyAskHdzs.class);
            if (flyAskHdzs != null && flyAskHdzs.getHxzsInfoList() != null && flyAskHdzs.getHxzsInfoList().size() != 0 && StringUtils.isNotBlank(flyAskHdzs.getHxzsInfoList().get(0).getHxzs())) {
                return true;
            }
        }


        return false;
    }

    //新增混凝土试验台账信息
    private void addTestLedgerHnt(Experiment experiment) {


        //根据台账 查询品控做的试验项目详情
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));
        //查询出品控的水泥试验项目配置
        List<TestProjectInfo> testProjectInfoList;
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        testProjectInfoList = testProjectInfoMapper.getList(new TestProjectInfo().setTestType(MaterialsEnum.CONCRETE.getTestProjectType()));


        //根据台账查询协会任务单id
        List<RwdextraExtend> rwdextraExtends = rwdextraExtendMapper.selectByExperimentId(experiment.getId());
        if (rwdextraExtends == null || rwdextraExtends.isEmpty()) {
            log.error("根据台账未查询到对应的协会任务单信息！台账id : " + experiment.getId());
            throw new RuntimeException("根据台账未查询到对应的协会任务单信息！台账id : " + experiment.getId());
        }


        //计数 用作是否有任务单未上传的
        int sum = 0;
        //如果任务单为上传 则进行上传操作
        for (RwdextraExtend rwdextraExtend : rwdextraExtends) {
            if (rwdextraExtend.getFrwdh() == null) {
                log.error("任务单信息有误！Frwdh 为空！台账id : " + experiment.getId() + "任务单id:" + rwdextraExtend.getId());
                throw new RuntimeException("任务单信息有误！Frwdh 为空！台账id : " + experiment.getId() + "任务单id:" + rwdextraExtend.getId());
            }
            if (rwdextraExtend == null || StringUtils.isBlank(rwdextraExtend.getProduceIndexId())) {
                sum++;
                log.info("根据台账未查询到对应的协会任务单信息！现进行重新上传操作！任务单id : " + rwdextraExtend.getId());
                Rwdextra rwdextra = rwdextraService.selectByFrwdh(rwdextraExtend.getFrwdh());
                if (rwdextra == null) {
                    log.error("任务单信息有误！根据Frwdh查询为空！台账id : " + experiment.getId() + "Frwdh:" + rwdextraExtend.getFrwdh());
                    throw new RuntimeException("任务单信息有误！根据Frwdh查询为空！台账id : " + experiment.getId() + "Frwdh:" + rwdextraExtend.getFrwdh());
                }

                /**新增任务单并上传到协会   新增操作到协会*/
                try {
                    taskListLaboratoryService.insertProduceHnt(rwdextra, null, true);
                } catch (Exception e) {
                    log.error("上传协会任务单失败：" + e.getMessage(), e);
                    //任务单扩展表   记录失败原因
                    rwdextraExtend.setReason(e.getMessage()).setStatus("0").setUpdateTime(new Date());
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);
                }
            }

        }


        //重新根据台账查询协会任务单id
        List<RwdextraExtend> rwdextraExtendNew = rwdextraExtendMapper.selectByExperimentId(experiment.getId());
        if (rwdextraExtendNew == null || rwdextraExtendNew.isEmpty()) {
            log.error("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
            throw new RuntimeException("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
        }

        //默认取第一条对应协会数据
        RwdextraExtend rwdextraExtend = rwdextraExtendNew.get(0);

        if (rwdextraExtend == null || StringUtils.isBlank(rwdextraExtend.getProduceIndexId())) {
            log.error("根据台账未查询到对应的协会任务单信息！任务单id : " + rwdextraExtend.getId());
            throw new RuntimeException("根据台账未查询到对应的协会任务单信息！任务单id : " + rwdextraExtend.getId());
        }

        //生成sampleNo
        String sampleNo = generateNew(experiment, list);

        log.info("查询出协会最大的样品编号为：" + sampleNo);
        //委托编号
        String consign = generateConsingId(experiment, list);


        for (ExperimentDetail detail : list) {

            for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                if (StringUtils.isBlank(detail.getTestProjectCode()) || StringUtils.isBlank(testProjectInfo.getTestCode())) {
                    continue;
                }
                if (testProjectInfo.getTestCode().equals(detail.getTestProjectCode()) && StringUtils.isNotBlank(testProjectInfo.getParameterName())) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        //如果所有项目都没做 则不生成协会台账信息
        if (set.isEmpty() || set.size() == 0) {
            log.error("未查询到对应试验项目，不需要上传台账信息！");
            return;
        }

        //龄期
        String lq = "";


        //当前年份后两位值
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearLastTwoDigits = String.valueOf(year).substring(2, 4);

        //默认查 08
        String val = yearLastTwoDigits + "08";

        //价格
        String prince = "";
        String sampleRegular = "";

        //品控的原材料名称 和 规格
        String materialsName = experiment.getMaterialsName();
        String materialsSpecs = experiment.getMaterialsSpecs();
        String ksdj = "";
        String ypdj = "";
        String itemName = "混凝土抗压";
        if (set.contains("抗渗等级")) {
            itemName = "混凝土抗渗";
            val = yearLastTwoDigits + "10";


            //混凝土抗压 获取临期值
            for (ExperimentDetail detail : list) {
                //混凝土抗压
                if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode())) {
                    ConcreteKsdj concreteKsdj = detail.getObjJson().toJavaObject(ConcreteKsdj.class);
                    if (concreteKsdj != null && StringUtils.isNotBlank(concreteKsdj.getLq())) {
                        lq = concreteKsdj.getLq();
                    }
                }
            }

            prince = "1000";
            sampleRegular = "1";
            ksdj = experiment.getKsdj();
        } else if (set.contains("抗压强度")) {
            itemName = "混凝土抗压";
            val = yearLastTwoDigits + "08";

            //混凝土抗压 获取临期值
            for (ExperimentDetail detail : list) {
                //混凝土抗压
                if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
                    ConcreteKyqd concreteKyqd = detail.getObjJson().toJavaObject(ConcreteKyqd.class);
                    if (concreteKyqd != null && StringUtils.isNotBlank(concreteKyqd.getLq())) {
                        lq = concreteKyqd.getLq();
                    }
                }
            }


            prince = "80";
        } else if (set.contains("抗折强度")) {
            itemName = "混凝土抗折";
            val = yearLastTwoDigits + "09";

            //混凝土抗折 获取临期值
            for (ExperimentDetail detail : list) {
                //混凝土抗折
                if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KZQD.getCode())) {
                    ConcreteKzqd concreteKzqd = detail.getObjJson().toJavaObject(ConcreteKzqd.class);
                    if (concreteKzqd != null && StringUtils.isNotBlank(concreteKzqd.getLq())) {
                        lq = concreteKzqd.getLq();
                    }
                }
            }

            ypdj = experiment.getSampleLevel();
            prince = "100";
        } else {
            //说明没包含项目 则不生成
            log.error("没有包含项目，不需要上传台账信息！");
            return;
        }


        //根据类型名称查找协会对应的 itemId
        Map<String, Object> itemItem = new HashMap<>();

        itemItem = m_uploadLaboratoryMapper.findItemItem(itemName);


        if (itemItem == null || itemItem.get("KindID") == null || itemItem.get("ItemID") == null) {
            log.error("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
            throw new RuntimeException("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
        }

        String kindID = "12"; //混凝土的默认12
        String itemID = itemItem.get("ItemID").toString();


        //代表数量
        Double behalfNumber = experiment.getRealBehalfNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }
        //品控厂家 和 批次
        String manufactor = experiment.getFactory();
        String batch = experiment.getBatch();


        if (materialsName == null || materialsSpecs == null) {
            log.error("品控数据有误！原材料名称或规格为空 materialsName=" + materialsName + "materialsSpecs =" + materialsSpecs);
            throw new RuntimeException("品控数据有误！原材料名称或规格为空 materialsName=" + materialsName + "materialsSpecs =" + materialsSpecs);
        }

        //1110为抗渗    1108 为抗压
        if ("1110".equals(itemID)) {
            materialsName = "混凝土抗渗试件";
        } else if ("1108".equals(itemID)) {
            materialsName = "混凝土立方体试件";
        } else if ("1109".equals(itemID)) {
            materialsName = "混凝土抗折试件";
        }
        //根据itemId + 原材料名称 查找 SampleID 和 项目 ParameterID
        List<Map<String, Object>> projectInformation = m_uploadLaboratoryMapper.findProjectInformationNew(materialsName, itemID);

        if (projectInformation == null || projectInformation.isEmpty()) {
            log.error("查询协会试验项目为空 materialsName=" + materialsName + "itemID=" + itemID + "projectInformation=" + projectInformation);
            throw new RuntimeException("查询协会试验项目为空 materialsName=" + materialsName + "itemID=" + itemID + "projectInformation=" + projectInformation);
        }


        //默认规格为0
        String gradeId = "0";
        String specId = "0";
        String samId = "";
        String ksdjGradeId = null;

        for (Map<String, Object> map : projectInformation) {

            String sjcc = null;
            if (map.get("ParameterName") != null) {
                //1110为抗渗 定死 抗渗等级   1108 为抗压  定死 抗压强度
                if ("1110".equals(itemID)) {
                    //抗渗定死规格  φ175㎜×φ185㎜×150㎜   111001301
                    specId = "111001301";
                    if (!"抗渗等级".equals(map.get("ParameterName").toString())) {
                        continue;
                    }
                } else if ("1108".equals(itemID)) {
                    //抗压强度 取json的 试件尺寸
                    for (ExperimentDetail detail : list) {
                        if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
                            ConcreteKyqd concreteKyqd = detail.getObjJson().toJavaObject(ConcreteKyqd.class);
                            if (concreteKyqd != null) {
                                sjcc = concreteKyqd.getSjcc();
                            }
                        }
                    }
                    if (!"抗压强度".equals(map.get("ParameterName").toString())) {
                        continue;
                    }
                } else if ("1109".equals(itemID)) {
                    //抗折定死规格     110901303
                    specId = "110901303";
                    if (!"抗折强度".equals(map.get("ParameterName").toString())) {
                        continue;
                    }
                }
            }

            //样品编号
            String sampleId = map.get("SampleID").toString();

            //根据sampleId + 规格 查询 协会对应的规格信息
            log.info("上传混凝土至协会，查询gradeId开始，规格SampleID：" + sampleId + " 品控材料规格：" + materialsSpecs);
            Map<String, Object> itemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, materialsSpecs);
            log.info("上传混凝土至协会，查询gradeId结束，查询数据：" + itemGrade);


            if (StringUtils.isNotBlank(ksdj)) {
                Map<String, Object> ksdjItemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, ksdj);
                if (ksdjItemGrade != null) {
                    ksdjGradeId = ksdjItemGrade.get("GradeID").toString();
                }
            }
            if (StringUtils.isNotBlank(ypdj)) {
                String mesTpzToKz = ConvertUtils.getMesTpzToKzyq(ypdj);
                if (StringUtils.isBlank(mesTpzToKz)) {
                    mesTpzToKz = mesTpzToKz + "MPa";
                }
                Map<String, Object> ksdjItemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, mesTpzToKz);
                if (ksdjItemGrade != null) {
                    ksdjGradeId = ksdjItemGrade.get("GradeID").toString();
                }
            }
            if (itemGrade != null) {
                gradeId = itemGrade.get("GradeID").toString();
            }
            if (sampleId != null) {
                samId = sampleId;
            }

            if ("0".equals(specId) && sjcc != null) {
                if (sjcc.contains("100")) {
                    sjcc = "100mm×100mm×100mm";
                } else if (sjcc.contains("150")) {
                    sjcc = "150mm×150mm×150mm";
                } else if (sjcc.contains("200")) {
                    sjcc = "200mm×200mm×200mm";
                }

                Map<String, Object> itemSpec = m_uploadLaboratoryMapper.findItemSpec(sampleId, sjcc);
                if (itemSpec != null) {
                    specId = itemSpec.get("SpecID").toString();

                }
            }


        }


        if ("0".equals(gradeId) && "0".equals(specId)) {
            log.error("查询 协会对应的规格信息为空！itemID =" + itemID + "materialsSpecs =" + materialsSpecs);
            throw new RuntimeException("查询 协会对应的规格信息为空！itemID =" + itemID + "materialsSpecs =" + materialsSpecs);
        }

        ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experiment.getId());
        /*if (shxhInfo == null) {
            //查询是否有关联过协会的台账编号了
            List<ShxhSynchronizedata> mapperList = shxhSynchronizedataMapper.getList(new ShxhSynchronizedata().setConsignId(consign));
            if (!mapperList.isEmpty()) {
                log.error("在执行新增上传混凝土台账时品控委托" + experiment.getExperimentNo() + ",新生成的协会委托" + consign + ",已存在对应关联！对应的品控委托id为：" + mapperList.get(0).getExperimentId());
                throw new RuntimeException("在执行新增上传混凝土台账时品控委托" + experiment.getExperimentNo() + ",新生成的协会委托" + consign + ",已存在对应关联！对应的品控委托id为：" + mapperList.get(0).getExperimentId());
            }
        }*/

        String SampleID = samId;
        String examParameter = "";
        String examParameterCn = "";
        String status = "";
        //根据原材料名称查找原材料项目
        //查出所有试验项目

        for (String str : set) {
            Map<String, Object> itemParameter = m_uploadLaboratoryMapper.findItemParameter(str, SampleID);

            if (itemParameter == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + SampleID);
                continue;
            }
            examParameter += itemParameter.get("ParameterID").toString() + ";";
            examParameterCn += str + ";";

            // （0,待检，1已检，2在检）    这里由于品控是保存抽样动作 就是试验中  所以协会直接改成 在检
            status += "0" + ";";
        }



        List<WtConsignWithSample> wtConsignWithSamples = new ArrayList<>();

        //新增样品
        addSample(experiment, sampleNo, lq, ksdjGradeId);

        //生成对应的  uploadFlag
        String wSUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), null);


        boolean isSample = false;
        String consignIdNew = "";
        int con = 0;
        //循环所有任务单 信息
        for (RwdextraExtend rwd : rwdextraExtendNew) {
            if (rwd == null || StringUtils.isBlank(rwd.getProduceIndexId())) {
                log.error("根据台账未查询到对应的协会任务单信息！任务单id : " + rwd.getId());
                throw new RuntimeException("根据台账未查询到对应的协会任务单信息！任务单id : " + rwd.getId());
            }

            //配合比编号
            String phbBh = "";
            //任务单编号
            String rwdbs = "";
            //工程名称
            String gcmc = "";
            //任务单备注
            String rwdbz = "";

            WtConsign wtConsign = new WtConsign();

            if (rwd.getProduceId() != null && !rwd.getProduceId().isEmpty()) {
                ProduceHnt produce_hnt = dataHntPhbMapper.findProduce_Hnt(rwd.getProduceId());
                if (produce_hnt == null) {
                    log.error("根据协会任务单查询协会信息有误！未查询到数据，协会任务单id : " + rwd.getProduceId());
                    throw new RuntimeException("根据协会任务单查询协会信息有误！未查询到数据，协会任务单id : " + rwd.getProduceId());
                }

                String hntrwdbs = produce_hnt.getProduceIndexId();

                if (StringUtils.isBlank(hntrwdbs)) {
                    log.error("根据协会任务单查询协会信息有误！任务单编号为空！协会任务单id : " + rwd.getProduceId());
                    throw new RuntimeException("根据协会任务单查询协会信息有误！任务单编号为空！协会任务单id : " + rwd.getProduceId());
                }

                //赋值
                if (StringUtils.isNotBlank(experiment.getPhb())) {
                    phbBh = experiment.getPhb();
                }
                if (produce_hnt.getProduceIndexId() != null) {
                    rwdbs = produce_hnt.getProduceIndexId();
                }
                if (produce_hnt.getProduceProjectName() != null) {
                    gcmc = produce_hnt.getProduceProjectName();
                }
                if (produce_hnt.getProduceMemo() != null) {
                    rwdbz = produce_hnt.getProduceMemo();
                }

                if (StringUtils.isBlank(rwdbs)) {
                    log.error("根据台账未查询到对应的协会任务单编号信息！任务单id : " + rwdextraExtend.getId());
                    return;
                }

                if (StringUtils.isBlank(phbBh)) {
                    log.error("根据台账未查询到对应的协会任务单配合比编号信息！任务单id : " + rwdextraExtend.getId());
                    return;
                }

                String wcUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), "0001-01-01");

                WtConsignWithSample wtConsignWithSample = new WtConsignWithSample();
                wtConsignWithSample.setConSignId(consign);
                wtConsignWithSample.setSampleId(sampleNo);
                wtConsignWithSample.setProduceIndexId(hntrwdbs);
                String wtConsignWithSampleUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", experiment.getEntrustTime(), "");
                wtConsignWithSample.setUploadFlag(wtConsignWithSampleUploadFlag);

                //根据任务单 查询协会委托 是否绑定过此任务单  且是同一试验项目  如果存在 则新增一条 wtSample 样品数据  否则 新增委托+样品
                List<WtConsign> wtConsignList = wtConsignMapper.findWTConsignListByProduceId(rwd.getProduceIndexId(), itemID);

                //说明存在  只需新增一条样品
                if (!wtConsignList.isEmpty() && wtConsignList.get(0).getItemId() != null && wtConsignList.get(0).getItemId().equals(itemID)) {
                    isSample = true;
                    wtConsignWithSample.setConSignId(wtConsignList.get(0).getConSignId());
                    consignIdNew = wtConsignList.get(0).getConSignId();
                    wtConsign = wtConsignList.get(0);
                } else {
                    //不存在 新增一条委托
                    String newId = keyPropertyMapper.getNewId();

                    WtConsign wC = new WtConsign();
                    wC.setId(newId);
                    String consignCon = "";
                    //委托编号
                    if (con == 0) {
                        consignCon = consign;
                    } else {
                        consignCon = generateConsingId(experiment, list);

                    }
                    wC.setConSignId(consignCon);

                    //赋值关联表里面的委托编号
                    wtConsignWithSample.setConSignId(consignCon);

                    wC.setSampleNo(sampleNo);
                    wC.setKindId(kindID);
                    wC.setItemId(itemID);
                    wC.setSamplingDate(experiment.getEntrustTime());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    if (rwdextraExtend.getPlantimeStart() == null) {
                        log.info("任务单计划时间为空，任务单信息：{}", rwdextraExtend);
                    } else {
                        try {
                            Date dateToStore = sdf.parse(rwdextraExtend.getPlantimeStart());
                            wC.setDeliverDate(dateToStore);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    }

                    wC.setProjectId("1");
                    wC.setWitnessNo("11");
                    wC.setSamplingNo("11");
                    wC.setProjectName(gcmc);
                    wC.setUploadFlag(wcUploadFlag);
                    wC.setExamConclusion(experiment.getConclusion());
                    wC.setExamKind("送样");
                    wC.setExamQuan("0");
                    wC.setProduceId(rwdbs);
                    wC.setProducePhbbh(phbBh);
                    wC.setMemo(rwdbz);//备注

                    wC.setTotalPrices(prince);
                    wC.setGetreportType("");
                    //新增WtConsign 信息
                    wtConsignMapper.insertWtConsign(wC);


                    rwd.setConsignId(wC.getConSignId());
                    //修改任务单 对应的协会委托编号
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwd);


                    WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemID);

                    String sampleNoSubstring = String.valueOf(Long.parseLong(sampleNo) + 1).substring(4);
                    String consignSubstring = String.valueOf(Long.parseLong(consignCon) + 1).substring(4);

                    if (wtCurrentNewId == null) {
                        log.info("新增混凝土WtCurrentNew，YearStr编号：【{}】，ItemId编号:【{}】，consignSubstring编号:【{}】，sampleNoSubstring编号:【{}】", yearLastTwoDigits, itemID, consignSubstring, sampleNoSubstring);
                        //新增
                        WtCurrentNew wtCurrentNew = new WtCurrentNew().setYearStr(yearLastTwoDigits).setItemId(itemID).setCurrentConsignId(consignSubstring).setCurrentSampleId(sampleNoSubstring);
                        wtCurrentIdMapper.addWtCurrentIdNew(wtCurrentNew);
                    } else {
                        log.info("修改混凝土WtCurrentNew，YearStr编号：【{}】，ItemId编号:【{}】，consignSubstring编号:【{}】，sampleNoSubstring编号:【{}】", yearLastTwoDigits, itemID, consignSubstring, sampleNoSubstring);
                        //修改
                        WtCurrentNew wtCurrentNew = new WtCurrentNew().setYearStr(yearLastTwoDigits).setItemId(itemID).setCurrentConsignId(consignSubstring).setCurrentSampleId(sampleNoSubstring);
                        wtCurrentIdMapper.updateWtCurrentNewId(wtCurrentNew);
                    }
                    con++;
                }


                wtConsignWithSamples.add(wtConsignWithSample);

            }
        }


        WtSample wS = new WtSample();
        wS.setSampleNo(sampleNo);
        //说明存在已有同一任务单
        if (isSample) {
            log.info("已有同一任务单 进入只新增协会样品");
            wS.setConSignId(consignIdNew);
        } else {
            wS.setConSignId(consign);
        }

        wS.setExamParameter(examParameter);
        wS.setExamParameterCn(examParameterCn);
        wS.setKindId(kindID);
        wS.setItemId(itemID);
        wS.setSampleId(SampleID);
        wS.setSpecId(specId);
        wS.setGradeId(gradeId);
        wS.setStatus(status);
        if (StringUtils.isNotBlank(lq)) {
            wS.setAgeTime(Integer.parseInt(lq));
        }
        wS.setSampleStatus("0");  // （0,待检，1已检，2在检）    这里由于品控是保存抽样动作 就是试验中  所以协会直接改成 在检
        wS.setSampleModify("0");

        wS.setDelegateQuan(behalfNumber == null ? "0" : String.valueOf(behalfNumber));

        wS.setDelegateQuanUnit("m³");
        wS.setProduceFactory("2");
        wS.setExamResult(experiment.getConclusion());

        wS.setMoldingDate(experiment.getMoldingTime());

        if (StringUtils.isNotBlank(sampleRegular)) {
            wS.setSampleRegular(sampleRegular);
        }


        wS.setUploadFlag(wSUploadFlag);

        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            wS.setIsProduce("1"); //是否生产任务(0为原材料,1为生产任务)
        } else {
            wS.setIsProduce("0"); //是否生产任务(0为原材料,1为生产任务)
        }


        wS.setPrince(prince);

        //新增WtSample 信息
        wtSampleMapper.insertWtSample(wS);


        //新增关联表
        for (WtConsignWithSample wt : wtConsignWithSamples) {
            List<WtConsignWithSample> wtConsignWithSample = wtConsignWithSampleMapper.findWtConsignWithSample(wt);
            if (!wtConsignWithSample.isEmpty()) {
                continue;
            }
            wtConsignWithSampleMapper.insertWtConsignWithSample(wt);
        }


        if (shxhInfo == null) {
            //新增对应关系
            ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata()
                    .setSampleId(sampleNo).setExperimentId(experiment.getId());
            if (isSample) {
                synchronizedata.setConsignId(consignIdNew);
            } else {
                synchronizedata.setConsignId(consign);
            }
            shxhSynchronizedataMapper.insertSelective(synchronizedata);
        } else {
            shxhInfo.setSampleId(sampleNo);
            if (isSample) {
                shxhInfo.setConsignId(consignIdNew);
            } else {
                shxhInfo.setConsignId(consign);
            }
            shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
        }

        log.info("同步新增混凝土委托+样品完成，协会台账编号：【{}】，样品编号；【{}】", consign, sampleNo);
        //修改品控委托状态
        experimentSampleTakeService.concreteSample(experiment.getId());
    }

    //修改混凝土试验台账信息
    private void updateTestLedgerHnt(Experiment experiment, String sampleNo, String consignId) {
        //根据台账 查询品控做的试验项目详情
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));

        String prince = "";
        //抗压强度 取json的 试件尺寸
        String sjcc = null;
        //抗折强度 取json的 试件尺寸
        String sjccKz = null;
        String lq = "";
        String ksdj = "";
        String ypdj = "";
        String itemID = "";
        for (ExperimentDetail detail : list) {
            if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
                prince = "80";
                ConcreteKyqd concreteKyqd = detail.getObjJson().toJavaObject(ConcreteKyqd.class);
                if (concreteKyqd != null) {
                    sjcc = concreteKyqd.getSjcc();
                    lq = concreteKyqd.getLq();
                }
                itemID = "1108";
            } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode())) {
                prince = "1000";
                ConcreteKsdj concreteKsdj = detail.getObjJson().toJavaObject(ConcreteKsdj.class);
                if (concreteKsdj != null && StringUtils.isNotBlank(concreteKsdj.getLq())) {
                    lq = concreteKsdj.getLq();
                }
                ksdj = experiment.getKsdj();
                itemID = "1110";
            } else if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KZQD.getCode())) {
                prince = "100";
                ConcreteKzqd concreteKzqd = detail.getObjJson().toJavaObject(ConcreteKzqd.class);
                if (concreteKzqd != null && StringUtils.isNotBlank(concreteKzqd.getLq())) {
                    lq = concreteKzqd.getLq();
                }
                if (concreteKzqd != null && StringUtils.isNotBlank(concreteKzqd.getSjcc())) {
                    sjccKz = concreteKzqd.getSjcc();
                }
                ypdj = experiment.getSampleLevel();
                itemID = "1109";
            }
        }

        String materialsName = experiment.getMaterialsName();
        String materialsSpecs = experiment.getMaterialsSpecs();

        //1110为抗渗    1108 为抗压
        if ("1110".equals(itemID)) {
            materialsName = "混凝土抗渗试件";
        } else if ("1108".equals(itemID)) {
            materialsName = "混凝土立方体试件";
        } else if ("1109".equals(itemID)) {
            materialsName = "混凝土抗折试件";
        } else {
            log.error("不需要上传的混凝土类型：【{}】", experiment);
            return;
        }
        //根据itemId + 原材料名称 查找 SampleID 和 项目 ParameterID
        List<Map<String, Object>> projectInformation = m_uploadLaboratoryMapper.findProjectInformationNew(materialsName, itemID);

        if (projectInformation == null || projectInformation.isEmpty()) {
            log.error("查询协会试验项目为空 materialsName=" + materialsName + "itemID=" + itemID + "projectInformation=" + projectInformation);
            throw new RuntimeException("查询协会试验项目为空 materialsName=" + materialsName + "itemID=" + itemID + "projectInformation=" + projectInformation);
        }

        String ksdjGradeId = "";
        String gradeId = null;

        for (Map<String, Object> map : projectInformation) {

            //样品编号
            String sampleId = map.get("SampleID").toString();

            //根据sampleId + 规格 查询 协会对应的规格信息
            log.info("上传混凝土至协会，查询gradeId开始，规格SampleID：" + sampleId + " 品控材料规格：" + materialsSpecs);
            Map<String, Object> itemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, materialsSpecs);
            log.info("上传混凝土至协会，查询gradeId结束，查询数据：" + itemGrade);

            if (itemGrade != null) {
                gradeId = itemGrade.get("GradeID").toString();
            }

            if (StringUtils.isNotBlank(ksdj)) {
                Map<String, Object> ksdjItemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, ksdj);
                if (ksdjItemGrade != null) {
                    ksdjGradeId = ksdjItemGrade.get("GradeID").toString();
                }
            }
            if (StringUtils.isNotBlank(ypdj)) {
                String mesTpzToKz = ConvertUtils.getMesTpzToKzyq(ypdj);
                if (StringUtils.isNotBlank(mesTpzToKz)) {
                    mesTpzToKz = mesTpzToKz + "MPa";
                }
                Map<String, Object> ksdjItemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, mesTpzToKz);
                if (ksdjItemGrade != null) {
                    ksdjGradeId = ksdjItemGrade.get("GradeID").toString();
                }
            }
        }


        //代表数量
        Double behalfNumber = experiment.getRealBehalfNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }

        WtSample wS = new WtSample();

        //抗压强度 重新查询试件尺寸 规格进行赋值修改
        if (sjcc != null) {
            Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);

            if (wtSampleList == null) {
                log.info("修改混凝土样品 + 台账时出现错误，未查询到协会样品数据，样品id:", sampleNo);
                return;
            }

            String sampleId = wtSampleList.get("SampleID").toString();
            if (sjcc.contains("100")) {
                sjcc = "100mm×100mm×100mm";
            } else if (sjcc.contains("150")) {
                sjcc = "150mm×150mm×150mm";
            } else if (sjcc.contains("200")) {
                sjcc = "200mm×200mm×200mm";
            }
            Map<String, Object> itemSpec = m_uploadLaboratoryMapper.findItemSpec(sampleId, sjcc);
            if (itemSpec != null) {
                wS.setSpecId(itemSpec.get("SpecID").toString());
            }

            //抗折事件尺寸
        } else if (sjccKz != null) {
            Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);

            if (wtSampleList == null) {
                log.info("修改混凝土样品 + 台账时出现错误，未查询到协会样品数据，样品id:", sampleNo);
                return;
            }

            String sampleId = wtSampleList.get("SampleID").toString();
            if (sjccKz.contains("400")) {
                sjccKz = "100㎜×100㎜×400㎜";
            } else if (sjccKz.contains("550")) {
                sjccKz = "100㎜×100㎜×400㎜";
            } else if (sjccKz.contains("600")) {
                sjccKz = "100㎜×100㎜×400㎜";
            }
            Map<String, Object> itemSpec = m_uploadLaboratoryMapper.findItemSpec(sampleId, sjccKz);
            if (itemSpec != null) {
                wS.setSpecId(itemSpec.get("SpecID").toString());
            }
        }

        wS.setSampleNo(sampleNo);
        wS.setPrince(prince);

        wS.setDelegateQuan(behalfNumber == null ? "0" : String.valueOf(behalfNumber));

        wS.setExamResult(experiment.getConclusion());

        if (gradeId != null) {
            wS.setGradeId(gradeId);
        }
        wS.setMoldingDate(experiment.getMoldingTime());

        if (StringUtils.isNotBlank(lq)) {
            wS.setAgeTime(Integer.parseInt(lq));
        }

        //新增WtSample 信息
        wtSampleMapper.updateWtSample(wS);


        List<WtConsign> wtConsignListBysampleId = wtConsignMapper.findWTConsignListBysampleId(sampleNo);
        if (wtConsignListBysampleId != null && wtConsignListBysampleId.size() > 0) {
            for (WtConsign wtConsign : wtConsignListBysampleId) {
                WtConsign wC = new WtConsign();
                wC.setConSignId(wtConsign.getConSignId());
                wC.setTotalPrices(prince);
                wC.setExamConclusion(experiment.getConclusion());
                wC.setSamplingDate(experiment.getEntrustTime());
                //新增WtConsign 信息
                wtConsignMapper.updateWtConsignNew(wC);
            }
        }


        //补全任务单+委托+样品  中间表
        if (StringUtils.isBlank(sampleNo) || StringUtils.isBlank(consignId)) {
            return;
        }


        List<WtConsignWithSample> wtConsignWithSamples = new ArrayList<>();

        List<RwdextraExtend> rwdextraExtends = rwdextraExtendMapper.selectByExperimentId(experiment.getId());
        if (rwdextraExtends == null || rwdextraExtends.isEmpty()) {
            log.error("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
            throw new RuntimeException("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
        }

        //如果任务单为上传 则进行上传操作
        for (RwdextraExtend rwdextraExtend : rwdextraExtends) {
            if (rwdextraExtend.getFrwdh() == null) {
                log.error("任务单信息有误！Frwdh 为空！台账id : " + experiment.getId() + "任务单id:" + rwdextraExtend.getId());
                throw new RuntimeException("任务单信息有误！Frwdh 为空！台账id : " + experiment.getId() + "任务单id:" + rwdextraExtend.getId());
            }
            if (rwdextraExtend == null || StringUtils.isBlank(rwdextraExtend.getProduceIndexId())) {
                log.info("根据台账未查询到对应的协会任务单信息！现进行重新上传操作！任务单id : " + rwdextraExtend.getId());
                Rwdextra rwdextra = rwdextraService.selectByFrwdh(rwdextraExtend.getFrwdh());
                if (rwdextra == null) {
                    log.error("任务单信息有误！根据Frwdh查询为空！台账id : " + experiment.getId() + "Frwdh:" + rwdextraExtend.getFrwdh());
                    throw new RuntimeException("任务单信息有误！根据Frwdh查询为空！台账id : " + experiment.getId() + "Frwdh:" + rwdextraExtend.getFrwdh());
                }

                /**新增任务单并上传到协会   新增操作到协会*/
                try {
                    taskListLaboratoryService.insertProduceHnt(rwdextra, null, true);
                } catch (Exception e) {
                    log.error("上传协会任务单失败：" + e.getMessage(), e);
                    //任务单扩展表   记录失败原因
                    rwdextraExtend.setReason(e.getMessage()).setStatus("0").setUpdateTime(new Date());
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);
                }
            }

        }


        //重新根据台账查询协会任务单id
        List<RwdextraExtend> rwdextraExtendNew = rwdextraExtendMapper.selectByExperimentId(experiment.getId());
        if (rwdextraExtendNew == null || rwdextraExtendNew.isEmpty()) {
            log.error("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
            throw new RuntimeException("根据台账未查询到对应的任务单信息！台账id : " + experiment.getId());
        }


        //当前年份后两位值
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearLastTwoDigits = String.valueOf(year).substring(2, 4);

        //循环所有任务单 信息
        for (RwdextraExtend rwd : rwdextraExtendNew) {
            if (rwd == null || StringUtils.isBlank(rwd.getProduceIndexId())) {
                log.error("根据台账未查询到对应的协会任务单信息！任务单id : " + rwd.getId());
                throw new RuntimeException("根据台账未查询到对应的协会任务单信息！任务单id : " + rwd.getId());
            }

            if (rwd.getProduceId() != null && !rwd.getProduceId().isEmpty()) {
                ProduceHnt produce_hnt = dataHntPhbMapper.findProduce_Hnt(rwd.getProduceId());
                if (produce_hnt == null) {
                    log.error("根据协会任务单查询协会信息有误！未查询到数据，协会任务单id : " + rwd.getProduceId());
                    throw new RuntimeException("根据协会任务单查询协会信息有误！未查询到数据，协会任务单id : " + rwd.getProduceId());
                }

                String hntrwdbs = produce_hnt.getProduceIndexId();

                //配合比编号
                String phbBh = "";
                //任务单编号
                String rwdbs = "";
                //工程名称
                String gcmc = "";
                //任务单备注
                String rwdbz = "";

                if (StringUtils.isBlank(hntrwdbs)) {
                    log.error("根据协会任务单查询协会信息有误！任务单编号为空！协会任务单id : " + rwd.getProduceId());
                    throw new RuntimeException("根据协会任务单查询协会信息有误！任务单编号为空！协会任务单id : " + rwd.getProduceId());
                }

                //赋值
                if (StringUtils.isNotBlank(experiment.getPhb())) {
                    phbBh = experiment.getPhb();
                }
                if (produce_hnt.getProduceIndexId() != null) {
                    rwdbs = produce_hnt.getProduceIndexId();
                }
                if (produce_hnt.getProduceMemo() != null) {
                    rwdbz = produce_hnt.getProduceMemo();
                }

                WtConsignWithSample wtConsignWithSample = new WtConsignWithSample();
                wtConsignWithSample.setSampleId(sampleNo);
                wtConsignWithSample.setProduceIndexId(hntrwdbs);
                String wtConsignWithSampleUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", experiment.getEntrustTime(), "");
                wtConsignWithSample.setUploadFlag(wtConsignWithSampleUploadFlag);


                //根据任务单+样品查询委托表 信息 如果不为空 则直接添加  如果为空 说明还未绑定过  则需新增一条委托 + 对应关联关系
                List<WtConsign> wtConList = wtConsignMapper.findWTConsignListByProduceId(rwdbs, itemID);
                if (!wtConList.isEmpty() && wtConList.size() > 0) {
                    wtConsignWithSample.setConSignId(wtConList.get(0).getConSignId());
                } else {
                    WtConsign consignModel = wtConsignMapper.findConsignId(consignId);

                    WtConsign wC = new WtConsign();
                    String newId = keyPropertyMapper.getNewId();
                    wC.setId(newId);
                    String consignCon = "";
                    //委托编号
                    consignCon = generateConsingId(experiment, list);
                    wC.setConSignId(consignCon);

                    //赋值关联表里面的委托编号
                    for (WtConsignWithSample consignWithSample : wtConsignWithSamples) {
                        if (consignWithSample.getProduceIndexId() != null && rwd.getProduceIndexId() != null && consignWithSample.getProduceIndexId().equals(rwd.getProduceIndexId())) {
                            consignWithSample.setConSignId(consignCon);
                        }
                    }

                    wC.setSampleNo(sampleNo);
                    wC.setKindId(consignModel.getKindId());
                    wC.setItemId(consignModel.getItemId());
                    wC.setSamplingDate(consignModel.getSamplingDate());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    if (rwd.getPlantimeStart() == null) {
                        log.info("任务单计划时间为空，任务单信息：{}", rwd);
                    } else {
                        try {
                            Date dateToStore = sdf.parse(rwd.getPlantimeStart());
                            wC.setDeliverDate(dateToStore);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    }

                    wC.setProjectId("1");
                    wC.setWitnessNo("11");
                    wC.setSamplingNo("11");
                    wC.setProjectName(consignModel.getProjectName());
                    String wcUploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), "0001-01-01");
                    wC.setUploadFlag(wcUploadFlag);
                    wC.setExamConclusion(experiment.getConclusion());
                    wC.setExamKind("送样");
                    wC.setExamQuan("0");
                    wC.setProduceId(rwdbs);
                    wC.setProducePhbbh(phbBh);
                    wC.setMemo(rwdbz);//备注

                    wC.setTotalPrices(prince);
                    wC.setGetreportType("");
                    //新增WtConsign 信息
                    wtConsignMapper.insertWtConsign(wC);

                    wtConsignWithSample.setConSignId(consignCon);


                    rwd.setConsignId(wC.getConSignId());
                    //修改任务单 对应的协会委托编号
                    rwdextraExtendMapper.updateByPrimaryKeySelective(rwd);


                    String consignSubstring = String.valueOf(Long.parseLong(consignCon) + 1).substring(4);

                    log.info("修改混凝土WtCurrentNew，YearStr编号：【{}】，ItemId编号:【{}】，consignSubstring编号:【{}】", yearLastTwoDigits, itemID, consignSubstring);
                    //修改
                    WtCurrentNew wtCurrentNew = new WtCurrentNew().setYearStr(yearLastTwoDigits).setItemId(itemID).setCurrentConsignId(consignSubstring);
                    wtCurrentIdMapper.updateWtCurrentNewId(wtCurrentNew);
                }

                wtConsignWithSamples.add(wtConsignWithSample);
            }

        }


        //根据样品删除对应关联关系
        wtConsignWithSampleMapper.delWtConsignWithSample(sampleNo);


        for (WtConsignWithSample wt : wtConsignWithSamples) {
            List<WtConsignWithSample> wtConsignWithSample = wtConsignWithSampleMapper.findWtConsignWithSample(wt);
            if (!wtConsignWithSample.isEmpty() && wtConsignWithSample.size() > 0) {
                continue;
            }
            wtConsignWithSampleMapper.insertWtConsignWithSample(wt);
        }


        //混凝土支持临期 + 样品 修改
        SampleUcHnt entity = new SampleUcHnt();
        entity.setSampleId(sampleNo);
        if (StringUtils.isNotBlank(lq)) {
            entity.setLingQi(Integer.parseInt(lq));
        }
        //包含抗渗 1110 itemId 则新增
        if (StringUtils.isNotBlank(ksdjGradeId)) {
            entity.setHNTKS_GradeID(ksdjGradeId);
        }

        sampleMapper.updateSampleUCHnt(entity);

        log.info("同步修改混凝土委托+样品完成，协会台账编号：【{}】，样品编号；【{}】", consignId, sampleNo);

    }

    //生成sampleNo
    private String generate(Experiment experiment) {

        String yearLastTwoDigits = null;
        //混凝土还是用当前时间  原材料用委托时间
        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            //当前年份后两位值
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        } else {
            if (experiment.getEntrustTime() == null) {
                log.error("品控委托时间为空! 委托编号为：" + experiment.getExperimentNo());
                return null;
            }

            Date entrustTime = experiment.getEntrustTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(entrustTime);
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        }


        //需要生成的 sampleNo
        String sampleNo = "";

        //如果是水泥  查询最大的Sample_Id
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            SampleUCShuiNi cementMaxSampleId = m_uploadLaboratoryMapper.findCementMaxSampleId();

            if (cementMaxSampleId == null || cementMaxSampleId.getSampleId() == null) {
                log.error("查询最大值 水泥样品Sample_ID为空！");
                return null;
            }

            String maxId = cementMaxSampleId.getSampleId();

            //如果获取的为当前年份  则用表里的最大值  否则 自己生成
            if (maxId.substring(0, 2).equals(yearLastTwoDigits)) {
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);
            } else {
                //生成规则  水泥：年份后两位+01+6位自增序号
                sampleNo = yearLastTwoDigits + maxId.substring(2, 4) + "000001";
            }


        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            SampleUCShuiNi fmhMaxSampleId = m_uploadLaboratoryMapper.findFMHMaxSampleId();

            if (fmhMaxSampleId == null || fmhMaxSampleId.getSampleId() == null) {
                log.error("查询最大值 粉煤灰样品Sample_ID为空！");
                return null;
            }

            String maxId = fmhMaxSampleId.getSampleId().toString();

            //如果获取的为当前年份  则用表里的最大值  否则 自己生成
            if (maxId.substring(0, 2).equals(yearLastTwoDigits)) {
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);
            } else {
                //生成规则  水泥：年份后两位+01+6位自增序号
                sampleNo = yearLastTwoDigits + maxId.substring(2, 4) + "000001";
            }


        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {

            //查询混凝土试验项目
            List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentId(experiment.getId()));

            List<String> stringList = new ArrayList<>();
            for (ExperimentDetail detail : list) {
                stringList.add(detail.getTestProjectName());
            }

            //默认查 08
            String val = yearLastTwoDigits + "08";

            if (stringList.contains("抗渗等级")) {
                val = yearLastTwoDigits + "10";
            } else if (stringList.contains("抗压强度")) {
                val = yearLastTwoDigits + "08";
            } else if (stringList.contains("抗折强度")) {
                val = yearLastTwoDigits + "09";
            }

            Map<String, Object> hntMaxSampleId = m_uploadLaboratoryMapper.findHNTMaxSampleId(val);

            String maxId = "";

            if (hntMaxSampleId == null || hntMaxSampleId.get("Sample_ID") == null) {
                maxId = val + "000001";

                sampleNo = maxId;
                return sampleNo;
            } else {
                maxId = hntMaxSampleId.get("Sample_ID").toString();
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);
            }

        } else {

            //样品编号生成规则（SampleNo）
            //水泥：年份后两位+01+6位自增序号
            //细骨料：年份后两位+03+6位自增序号
            //粗骨料：年份后两位+02+6位自增序号
            //粉煤灰：年份后两位+17+6位自增序号
            //矿渣粉：年份后两位+24+6位自增序号
            //外加剂：年份后两位+16+6位自增序号

            String value = "";

            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "03";

                Map<String, Object> defMaxSampleId = m_uploadLaboratoryMapper.findDefaultMaxSampleId(value);

                //查询为空 说明为 新的一年 数据  自己生成
                if (defMaxSampleId == null) {

                    //生成规则  水泥：年份后两位+01+6位自增序号
                    sampleNo = yearLastTwoDigits + "03" + "000001";
                    return sampleNo;

                } else if (defMaxSampleId.get("Sample_ID") == null) {
                    log.error("查询最大值 细骨料样品Sample_ID为空！");
                    return null;
                }

                String maxId = defMaxSampleId.get("Sample_ID").toString();
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);


            } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "02";

                Map<String, Object> defMaxSampleId = m_uploadLaboratoryMapper.findDefaultMaxSampleId(value);

                //查询为空 说明为 新的一年 数据  自己生成
                if (defMaxSampleId == null) {

                    //生成规则  水泥：年份后两位+01+6位自增序号
                    sampleNo = yearLastTwoDigits + "02" + "000001";

                    return sampleNo;

                } else if (defMaxSampleId.get("Sample_ID") == null) {
                    log.error("查询最大值 粗骨料样品Sample_ID为空！");
                    return null;
                }

                String maxId = defMaxSampleId.get("Sample_ID").toString();
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);


            } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "24";

                Map<String, Object> defMaxSampleId = m_uploadLaboratoryMapper.findDefaultMaxSampleId(value);

                //查询为空 说明为 新的一年 数据  自己生成
                if (defMaxSampleId == null) {

                    //生成规则  水泥：年份后两位+01+6位自增序号
                    sampleNo = yearLastTwoDigits + "24" + "000001";

                    return sampleNo;

                } else if (defMaxSampleId.get("Sample_ID") == null) {
                    log.error("查询最大值 矿渣粉样品Sample_ID为空！");
                    return null;
                }

                String maxId = defMaxSampleId.get("Sample_ID").toString();
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);


            } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "16";

                Map<String, Object> defMaxSampleId = m_uploadLaboratoryMapper.findDefaultMaxSampleId(value);


                //查询为空 说明为 新的一年 数据  自己生成
                if (defMaxSampleId == null) {

                    //生成规则  水泥：年份后两位+01+6位自增序号
                    sampleNo = yearLastTwoDigits + "16" + "000001";

                    return sampleNo;

                } else if (defMaxSampleId.get("Sample_ID") == null) {
                    log.error("查询最大值 外加剂样品Sample_ID为空！");
                    return null;
                }

                String maxId = defMaxSampleId.get("Sample_ID").toString();
                //默认+1
                sampleNo = String.valueOf(Long.parseLong(maxId) + 1);

            }

        }


        return sampleNo;
    }

    //生成sampleNo(新)
    private String generateNew(Experiment experiment, List<ExperimentDetail> detailList) {

        String yearLastTwoDigits = null;
        //混凝土还是用当前时间  原材料用委托时间
        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            //当前年份后两位值
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        } else {
            if (experiment.getEntrustTime() == null) {
                log.error("品控委托时间为空! 委托编号为：" + experiment.getExperimentNo());
                return null;
            }

            Date entrustTime = experiment.getEntrustTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(entrustTime);
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        }


        //需要生成的 sampleNo
        String sampleNo = "";

        String value = "";
        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {

            List<String> stringList = new ArrayList<>();
            for (ExperimentDetail detail : detailList) {
                stringList.add(detail.getTestProjectName());
            }

            String itemId = "";
            if (stringList.contains("抗渗等级")) {
                itemId = "1110";
                value = yearLastTwoDigits + "10";
            } else if (stringList.contains("抗压强度")) {
                itemId = "1108";
                value = yearLastTwoDigits + "08";
            } else if (stringList.contains("抗折强度")) {
                itemId = "1109";
                value = yearLastTwoDigits + "09";
            }

            WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemId);
            if (wtCurrentNewId == null) {
                log.info("查询WT_CurrentNewId数据为空 itemId{},year{}", itemId, yearLastTwoDigits);
                sampleNo = value + "000001";
            } else {
                log.info("查询WT_CurrentNewId数据 itemId{},year{},CurrentSampleId{}", itemId, yearLastTwoDigits, wtCurrentNewId.getCurrentSampleId());
                sampleNo = String.valueOf(Long.parseLong(value + wtCurrentNewId.getCurrentSampleId()));
            }

        } else {
            //原材料

            //根据类型名称查找协会对应的 itemId
            Map<String, Object> itemItem = new HashMap<>();
            MaterialsEnum materialsEnum = MaterialsEnum.selectByCode(experiment.getExperimentType());
            if (materialsEnum == null || materialsEnum.getName() == null) {
                log.error("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
                throw new RuntimeException("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
            } else if (materialsEnum.getName().equals(MaterialsEnum.SLAG.getName())) {
                //品控材料叫矿渣粉  上海协会叫矿渣微粉
                itemItem = m_uploadLaboratoryMapper.findItemItem("矿渣微粉");
            } else {
                itemItem = m_uploadLaboratoryMapper.findItemItem(materialsEnum.getName());
            }

            if (itemItem == null || itemItem.get("KindID") == null || itemItem.get("ItemID") == null) {
                log.error("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
                throw new RuntimeException("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
            }

            String itemID = itemItem.get("ItemID").toString();


            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "03";

            } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "02";

            } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "24";

            } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "16";

            } else if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "01";

            } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "17";

            }

            WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemID);
            if (wtCurrentNewId == null) {
                log.info("查询WT_CurrentNewId数据为空 itemId{},year{}", itemID, yearLastTwoDigits);
                sampleNo = value + "000001";
            } else {
                log.info("查询WT_CurrentNewId数据 itemId{},year{},CurrentSampleId{}", itemID, yearLastTwoDigits, wtCurrentNewId.getCurrentSampleId());
                sampleNo = String.valueOf(Long.parseLong(value + wtCurrentNewId.getCurrentSampleId()));
            }


        }

        Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);
        if (wtSampleList != null && wtSampleList.get("Sample_ID") != null) {
            log.info("查询委托有值 则 +1：" + sampleNo);
            sampleNo = String.valueOf(Long.parseLong(sampleNo) + 1);


            Map<String, Object> wtSampleListNew = wtSampleMapper.findWTSampleList(sampleNo);
            if (wtSampleListNew != null && wtSampleListNew.get("Sample_ID") != null) {
                log.info("查询委托+1后也有值  则取委托表最大值：" + sampleNo);
                log.info("查询委托请求数据为：" + value);
                Map<String, Object> wtSampleListMaxId = wtSampleMapper.findWTSampleListMaxId(value);
                if (wtSampleListMaxId == null || wtSampleListMaxId.get("Sample_ID") == null) {
                    log.error("查询最大值WT_Sample表数据为空！ value =" + value);
                    throw new RuntimeException("查询最大值WT_Sample表数据为空！");
                }
                String string = wtSampleListMaxId.get("Sample_ID").toString();
                log.info("查询委托样品编号数据为：" + string);
                sampleNo = String.valueOf(Long.parseLong(string) + 1);
                log.info("查询委托样品编号数据+1后：" + sampleNo);
            }
        }
        log.info("生成的样品编号为：" + sampleNo);

        return sampleNo;
    }

    //生成consingId
    private String generateConsingId(Experiment experiment, List<ExperimentDetail> detailList) {

        String yearLastTwoDigits = null;
        //混凝土还是用当前时间  原材料用委托时间
        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {
            //当前年份后两位值
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        } else {
            if (experiment.getEntrustTime() == null) {
                log.error("品控委托时间为空! 委托编号为：" + experiment.getExperimentNo());
                return null;
            }

            Date entrustTime = experiment.getEntrustTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(entrustTime);
            int year = calendar.get(Calendar.YEAR);
            yearLastTwoDigits = String.valueOf(year).substring(2, 4);
        }


        //需要生成的 consingId
        String consingId = "";

        String value = "";
        if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {

            List<String> stringList = new ArrayList<>();
            for (ExperimentDetail detail : detailList) {
                stringList.add(detail.getTestProjectName());
            }

            String itemId = "";
            if (stringList.contains("抗渗等级")) {
                itemId = "1110";
                value = yearLastTwoDigits + "10";
            } else if (stringList.contains("抗压强度")) {
                itemId = "1108";
                value = yearLastTwoDigits + "08";
            } else if (stringList.contains("抗折强度")) {
                itemId = "1109";
                value = yearLastTwoDigits + "09";
            }

            WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemId);
            if (wtCurrentNewId == null) {
                log.info("查询WT_CurrentNewId数据为空 itemId{},year{}", itemId, yearLastTwoDigits);
                consingId = value + "000001";
            } else {
                log.info("查询WT_CurrentNewId数据 itemId{},year{},CurrentConsignId{}", itemId, yearLastTwoDigits, wtCurrentNewId.getCurrentConsignId());
                consingId = String.valueOf(Long.parseLong(value + wtCurrentNewId.getCurrentConsignId()));
            }

        } else {
            //原材料

            //根据类型名称查找协会对应的 itemId
            Map<String, Object> itemItem = new HashMap<>();
            MaterialsEnum materialsEnum = MaterialsEnum.selectByCode(experiment.getExperimentType());
            if (materialsEnum == null || materialsEnum.getName() == null) {
                log.error("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
                throw new RuntimeException("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
            } else if (materialsEnum.getName().equals(MaterialsEnum.SLAG.getName())) {
                //品控材料叫矿渣粉  上海协会叫矿渣微粉
                itemItem = m_uploadLaboratoryMapper.findItemItem("矿渣微粉");
            } else {
                itemItem = m_uploadLaboratoryMapper.findItemItem(materialsEnum.getName());
            }

            if (itemItem == null || itemItem.get("KindID") == null || itemItem.get("ItemID") == null) {
                log.error("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
                throw new RuntimeException("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
            }

            String itemID = itemItem.get("ItemID").toString();


            if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "03";

            } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "02";

            } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "24";

            } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "16";

            } else if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "01";

            } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
                value = yearLastTwoDigits + "17";

            }

            WtCurrentNew wtCurrentNewId = wtCurrentIdMapper.findWTCurrentNewId(yearLastTwoDigits, itemID);
            if (wtCurrentNewId == null) {
                log.info("查询WT_CurrentNewId数据为空 itemId{},year{}", itemID, yearLastTwoDigits);
                consingId = value + "000001";
            } else {
                log.info("查询WT_CurrentNewId数据 itemId{},year{},CurrentConsignId{}", itemID, yearLastTwoDigits, wtCurrentNewId.getCurrentConsignId());
                consingId = String.valueOf(Long.parseLong(value + wtCurrentNewId.getCurrentConsignId()));
            }


        }

        WtConsign wtConsign = wtConsignMapper.findConsignId(consingId);
        if (wtConsign != null && wtConsign.getConSignId() != null) {
            log.info("查询委托有值 则 +1：" + consingId);
            consingId = String.valueOf(Long.parseLong(consingId) + 1);


            WtConsign wtConsignNew = wtConsignMapper.findConsignId(consingId);
            if (wtConsignNew != null && wtConsignNew.getConSignId() != null) {
                log.info("查询委托+1后也有值  则取委托表最大值：" + consingId);
                log.info("查询委托请求数据为：" + value);
                WtConsign hntMaxConsignId = wtConsignMapper.findHNTMaxConsignId(value);
                if (hntMaxConsignId == null || hntMaxConsignId.getConSignId() == null) {
                    log.error("查询最大值WT_Consign表数据为空！ value =" + value);
                    throw new RuntimeException("查询最大值WT_Consign表数据为空！");
                }
                String string = hntMaxConsignId.getConSignId();
                log.info("查询委托编号数据为：" + string);
                consingId = String.valueOf(Long.parseLong(string) + 1);
                log.info("查询委托编号数据+1后：" + consingId);
            }
        }
        log.info("生成的委托编号为：" + consingId);

        return consingId;
    }

    private void addSample(Experiment experiment, String sampleNo, String lq, String gradeId) {

        //生成对应的  uploadFlag
        String uploadFlag = "";

        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {

            //生成对应的  uploadFlag
            uploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), null);

            //新增水泥样品
            SampleUCShuiNi entity = new SampleUCShuiNi().setSampleId(sampleNo).setUploadFlag(uploadFlag);

            List<SampleUCShuiNi> sampleUCShuiNi = sampleMapper.findSampleUCShuiNi(entity);
            if (sampleUCShuiNi == null || sampleUCShuiNi.isEmpty() || sampleUCShuiNi.size() == 0) {
                sampleMapper.insertSampleUCShuiNi(entity);
            }

        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            uploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), null);

            //新增粉煤灰样品
            SampleUCShuiNi entity = new SampleUCShuiNi().setSampleId(sampleNo).setUploadFlag(uploadFlag);

            List<SampleUCShuiNi> sampleUCFMH = sampleMapper.findSampleUCFMH(entity);
            if (sampleUCFMH == null || sampleUCFMH.isEmpty() || sampleUCFMH.size() == 0) {
                sampleMapper.insertSampleUCFMH(entity);
            }


        } else if (MaterialsEnum.CONCRETE.getCode().equals(experiment.getExperimentType())) {

            uploadFlag = UploadFlagUtils.CtoGB_Num("0000000000", "z", new Date(), null);

            SampleUcHnt entity = new SampleUcHnt();
            entity.setSampleId(sampleNo);
            entity.setUploadFlag(uploadFlag);
            entity.setHntYangHuTianJian("标准养护");
            entity.setZhiZuoRiQi(experiment.getEntrustTime());
            if (StringUtils.isNotBlank(lq)) {
                entity.setLingQi(Integer.parseInt(lq));
            }
            //包含抗渗 1110 itemId 则新增
            if (StringUtils.isNotBlank(gradeId)) {
                entity.setHNTKS_GradeID(gradeId);
            }

            sampleMapper.insertSampleUCHnt(entity);


        } else {
            uploadFlag = UploadFlagUtils.CtoGB_Num(sampleNo, "z", new Date(), null);

            //新增粗骨料 细骨料 矿渣粉  外加剂 样品
            SampleUCShuiNi entity = new SampleUCShuiNi().setSampleId(sampleNo).setUploadFlag(uploadFlag);

            List<SampleUCShuiNi> sampleUCDef = sampleMapper.findSampleUCDef(entity);
            if (sampleUCDef == null || sampleUCDef.isEmpty() || sampleUCDef.size() == 0) {
                sampleMapper.insertSampleUCDef(entity);
            }
        }

    }


    //材料进场
    private ImportList materialEntry(Experiment experiment, String sampleNo) {


        //查询所有类型批检配置
        List<ExperimentGenConfig> experimentGenConfigList = experimentGenConfigMapper.getList(new ExperimentGenConfig().setCheckType(CheckEnum.BATCH.getCode()));

        //厂家取值
        String cj = "";
        //1 -- 同一厂家   2 -- 同一供应商
        String qualifiedType = "";

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.CEMENT.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("水泥配置项为：" + qualifiedType);
                    }
                }
            }

        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.FLY.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("粉煤灰配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.SLAG.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("矿渣粉配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.COARSE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("粗骨料配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.FINE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("细骨料配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.ADMIXTURE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("外加剂配置项为：" + qualifiedType);
                    }
                }
            }
        }


        //1 -- 同一厂家   2 -- 同一供应商
        if ("1".equals(qualifiedType)) {
            cj = experiment.getFactory();
            log.info("厂家值为：" + experiment.getFactory());
        } else if ("2".equals(qualifiedType)) {
            cj = experiment.getSupplyCompanyName();
            log.info("供应商值为：" + experiment.getSupplyCompanyName());
        }

        if (cj != null) {
            if (cj.contains("（砂）")) {
                cj = cj.substring(0, cj.indexOf("（砂）"));
            } else if (cj.contains("(砂)")) {
                cj = cj.substring(0, cj.indexOf("(砂)"));
            } else if (cj.contains("（石）")) {
                cj = cj.substring(0, cj.indexOf("（石）"));
            } else if (cj.contains("(石)")) {
                cj = cj.substring(0, cj.indexOf("(石)"));
            } else if (cj.contains("（泥）")) {
                cj = cj.substring(0, cj.indexOf("（泥）"));
            } else if (cj.contains("(泥)")) {
                cj = cj.substring(0, cj.indexOf("(泥)"));
            }
        }

        //备案证
        String recordCertificate = experiment.getCertificateNo();
        log.info("备案证值为：" + experiment.getCertificateNo());

        //根据类型名称查找协会对应的 itemId
        Map<String, Object> itemItem = new HashMap<>();
        MaterialsEnum materialsEnum = MaterialsEnum.selectByCode(experiment.getExperimentType());
        if (materialsEnum == null || materialsEnum.getName() == null) {
            log.error("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
            throw new RuntimeException("MaterialsEnum枚举类翻译错误！ExperimentType =" + experiment.getExperimentType());
        } else if (materialsEnum.getName().equals(MaterialsEnum.SLAG.getName())) {
            //品控材料叫矿渣粉  上海协会叫矿渣微粉
            itemItem = m_uploadLaboratoryMapper.findItemItem("矿渣微粉");
        } else {
            itemItem = m_uploadLaboratoryMapper.findItemItem(materialsEnum.getName());
        }

        if (itemItem == null || itemItem.get("KindID") == null || itemItem.get("ItemID") == null) {
            log.error("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
            throw new RuntimeException("根据类型名称查找协会对应的 itemId错误！查询值为空！itemItem =" + itemItem);
        }

        String kindID = itemItem.get("KindID").toString();
        String itemID = itemItem.get("ItemID").toString();

        //品控的原材料名称 和 规格
        String materialsName = experiment.getMaterialsName();
        String materialsSpecs = experiment.getMaterialsSpecs();
        //代表数量
        Double behalfNumber = experiment.getRealMaterialNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }


        if (materialsName == null || materialsSpecs == null) {
            log.error("品控数据有误！原材料名称或规格为空 materialsName=" + materialsName + "materialsSpecs =" + materialsSpecs);
            throw new RuntimeException("品控数据有误！原材料名称或规格为空 materialsName=" + materialsName + "materialsSpecs =" + materialsSpecs);
        }

        //品控材料id
        Long spId = experiment.getSpecId();

        if (spId == null) {
            log.error("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
            throw new RuntimeException("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
        }
        //查询对应同步的协会材料数据
        MaterialsSpecConfig materialsSpecConfig = materialsSpecConfigMapper.loadById(spId);

        if (materialsSpecConfig == null) {
            log.error("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
            throw new RuntimeException("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
        }

        //协会总规格id
        String sampleId = materialsSpecConfig.getSampleId();

        if (sampleId == null) {
            log.error("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
            throw new RuntimeException("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
        }


        //当前年份后两位值
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String yearLastTwoDigits = String.valueOf(year);

        //查询当前年份最大值 入场材料importId
        ImportList importListMaxImportId = importListMapper.findImportListMaxImportId(yearLastTwoDigits);


        //默认最大值 +1
        String importId = null;

        //入场编号生成规则（Import_ID）
        //年份+六位自增序号(2024001002)
        //查询为空则说明为新的一年
        if (importListMaxImportId == null) {
            importId = yearLastTwoDigits + "000001";
        } else {
            String importimportListMaxImportId = importListMaxImportId.getImportId();
            //判断最大值是否是当前年份
            if (importimportListMaxImportId.substring(0, 4).equals(yearLastTwoDigits)) {
                //默认最大值 +1
                importId = String.valueOf(Long.parseLong(importimportListMaxImportId) + 1);

            } else {
                importId = yearLastTwoDigits + "000001";
            }
        }


        WtCurrent wtCurrentId = wtCurrentIdMapper.findWTCurrentId(yearLastTwoDigits);
        if (wtCurrentId == null) {
            //新增WT_CurrentId表
            WtCurrent wtCurrent = new WtCurrent().setYearStr(yearLastTwoDigits).setCurrentImportId(String.valueOf(Integer.parseInt(importId) + 1))
                    .setCurrentConsignId("0000000001").setCurrentSampleId("0000000001").setCurrentProduceId("0000000001");
            wtCurrentIdMapper.addWtCurrentId(wtCurrent);
        } else {
            //修改WT_CurrentId表
            WtCurrent wtCurrent = new WtCurrent().setYearStr(yearLastTwoDigits).setCurrentImportId(String.valueOf(Integer.parseInt(importId) + 1));
            wtCurrentIdMapper.updateWtCurrentId(wtCurrent);
        }

        //默认规格为0
        String gradeId = materialsSpecConfig.getGradeId();
        String specId = materialsSpecConfig.getSpecId();
        if (gradeId == null || StringUtils.isBlank(gradeId)) {
            gradeId = "0";
        }
        if (specId == null || StringUtils.isBlank(specId)) {
            specId = "0";
        }

        String samId = sampleId;

      /*  if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType()) || MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())
                || MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, materialsSpecs);

            if (itemGrade != null && itemGrade.get("GradeID") != null) {
                gradeId = itemGrade.get("GradeID").toString();
                samId = sampleId;
            }
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType()) || MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemSpec = m_uploadLaboratoryMapper.findItemSpec(sampleId, materialsSpecs);
            if (itemSpec != null && itemSpec.get("SpecID") != null) {
                specId = itemSpec.get("SpecID").toString();
                samId = sampleId;
            }

        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemGradeAndItemSpec = m_uploadLaboratoryMapper.findItemGradeAndItemSpec(sampleId, materialsSpecs);

            if (itemGradeAndItemSpec != null && itemGradeAndItemSpec.get("GradeID") != null) {
                gradeId = itemGradeAndItemSpec.get("GradeID").toString();

                if (itemGradeAndItemSpec != null && itemGradeAndItemSpec.get("SpecID") != null) {
                    specId = itemGradeAndItemSpec.get("SpecID").toString();

                    samId = sampleId;
                }
            }
        }


        if ("0".equals(gradeId) && "0".equals(specId)) {
            log.error("查询 协会对应的规格信息为空！itemID =" + itemID + "materialsSpecs =" + materialsSpecs);
            throw new RuntimeException("查询 协会对应的规格信息为空！itemID =" + itemID + "materialsSpecs =" + materialsSpecs);
        }
*/

        //生成对应的  uploadFlag
        String uploadFlag = UploadFlagUtils.CtoGB_Num(importId, "z", new Date(), null);


        //新增 材料入场   import_list 表
        //批号 采用样品编号 后 三位
        String groupId = null;
        if (StringUtils.isNotBlank(experiment.getBatchNumber())) {
            groupId = experiment.getBatchNumber();
        } else {
            groupId = sampleNo.substring(sampleNo.length() - 3);
        }


        ImportList importList = new ImportList().setImportDate(new Date()).setKindId(kindID).setItemId(itemID)
                .setSampleID(samId).setGradeId(gradeId).setImportId(importId).setSpecId(specId)
                .setFactoryName(cj).setRecordCertificate(recordCertificate).setGroupId(groupId).setUploadFlag(uploadFlag)
                .setProdinUnit("t").setCheckFlag("0").setSystemReport("1").setFinish("0").setSampling("0");//默认1 已取样
        if (behalfNumber != null) {
            importList.setProdinQuan(String.valueOf(behalfNumber));
        } else {
            importList.setProdinQuan("0");
        }

        importListMapper.addImportList(importList);

        return importList;
    }

    //修改进场
    private void updateMaterialEntry(Experiment experiment, String importId) {
        log.info("修改原材料进料数据开始...");


        //查询所有类型批检配置
        List<ExperimentGenConfig> experimentGenConfigList = experimentGenConfigMapper.getList(new ExperimentGenConfig().setCheckType(CheckEnum.BATCH.getCode()));

        //厂家取值
        String cj = "";
        //1 -- 同一厂家   2 -- 同一供应商
        String qualifiedType = "";

        //原材料类型为 ：水泥
        if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.CEMENT.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("水泥配置项为：" + qualifiedType);
                    }
                }
            }

        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.FLY.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("粉煤灰配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.SLAG.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("矿渣粉配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.COARSE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("粗骨料配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.FINE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("细骨料配置项为：" + qualifiedType);
                    }
                }
            }
        } else if (MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {
            for (ExperimentGenConfig genConfig : experimentGenConfigList) {
                if (MaterialsEnum.ADMIXTURE.getCode().equals(genConfig.getExperimentType())) {
                    if (genConfig.getQualifiedType() != null) {
                        qualifiedType = String.valueOf(genConfig.getQualifiedType());
                        log.info("外加剂配置项为：" + qualifiedType);
                    }
                }
            }
        }


        //1 -- 同一厂家   2 -- 同一供应商
        if ("1".equals(qualifiedType)) {
            cj = experiment.getFactory();
            log.info("厂家值为：" + experiment.getFactory());
        } else if ("2".equals(qualifiedType)) {
            cj = experiment.getSupplyCompanyName();
            log.info("供应商值为：" + experiment.getSupplyCompanyName());
        }

        if (cj != null) {
            if (cj.contains("（砂）")) {
                cj = cj.substring(0, cj.indexOf("（砂）"));
            } else if (cj.contains("(砂)")) {
                cj = cj.substring(0, cj.indexOf("(砂)"));
            } else if (cj.contains("（石）")) {
                cj = cj.substring(0, cj.indexOf("（石）"));
            } else if (cj.contains("(石)")) {
                cj = cj.substring(0, cj.indexOf("(石)"));
            } else if (cj.contains("（泥）")) {
                cj = cj.substring(0, cj.indexOf("（泥）"));
            } else if (cj.contains("(泥)")) {
                cj = cj.substring(0, cj.indexOf("(泥)"));
            }
        }

        //备案证
        String recordCertificate = experiment.getCertificateNo();
        log.info("备案证值为：" + experiment.getCertificateNo());


        //品控的原材料名称 和 规格
        String materialsName = experiment.getMaterialsName();
        String materialsSpecs = experiment.getMaterialsSpecs();

        //品控材料id
        Long spId = experiment.getSpecId();

        if (spId == null) {
            log.error("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
            throw new RuntimeException("品控数据有误！对应材料表id为空！ 品控台账id=" + experiment.getId() + "委托编号 =" + experiment.getExperimentNo());
        }
        //查询对应同步的协会材料数据
        MaterialsSpecConfig materialsSpecConfig = materialsSpecConfigMapper.loadById(spId);

        if (materialsSpecConfig == null) {
            log.error("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
            throw new RuntimeException("品控数据有误！查询对应同步的协会材料数据为空！ 材料id=" + spId);
        }

        //协会总规格id
        String sampleId = materialsSpecConfig.getSampleId();

        if (sampleId == null) {
            log.error("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
            throw new RuntimeException("品控数据有误！对应材料表协会sampleId为空！材料id=" + spId);
        }


        ImportList importList = new ImportList().setImportId(importId).setFactoryName(cj).setRecordCertificate(recordCertificate);

        //代表数量
        Double behalfNumber = experiment.getRealMaterialNumber();
        if (behalfNumber == null) {
            behalfNumber = experiment.getBehalfNumber();
        }

        if (behalfNumber != null) {
            importList.setProdinQuan(String.valueOf(behalfNumber));
        } else {
            importList.setProdinQuan("0");
        }


        //默认规格为0
        String gradeId = materialsSpecConfig.getGradeId();
        String specId = materialsSpecConfig.getSpecId();
        if (gradeId == null || StringUtils.isBlank(gradeId)) {
            gradeId = "0";
        }
        if (specId == null || StringUtils.isBlank(specId)) {
            specId = "0";
        }

        String samId = sampleId;

      /*  if (MaterialsEnum.CEMENT.getCode().equals(experiment.getExperimentType()) || MaterialsEnum.SLAG.getCode().equals(experiment.getExperimentType())
                || MaterialsEnum.ADMIXTURE.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemGrade = m_uploadLaboratoryMapper.findItemGrade(sampleId, materialsSpecs);

            if (itemGrade != null && itemGrade.get("GradeID") != null) {
                gradeId = itemGrade.get("GradeID").toString();
                samId = sampleId;
            }
        } else if (MaterialsEnum.COARSE.getCode().equals(experiment.getExperimentType()) || MaterialsEnum.FINE.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemSpec = m_uploadLaboratoryMapper.findItemSpec(sampleId, materialsSpecs);
            if (itemSpec != null && itemSpec.get("SpecID") != null) {
                specId = itemSpec.get("SpecID").toString();
                samId = sampleId;
            }

        } else if (MaterialsEnum.FLY.getCode().equals(experiment.getExperimentType())) {

            //根据sampleId + 规格 查询 协会对应的规格信息
            Map<String, Object> itemGradeAndItemSpec = m_uploadLaboratoryMapper.findItemGradeAndItemSpec(sampleId, materialsSpecs);

            if (itemGradeAndItemSpec != null && itemGradeAndItemSpec.get("GradeID") != null) {
                gradeId = itemGradeAndItemSpec.get("GradeID").toString();

                if (itemGradeAndItemSpec != null && itemGradeAndItemSpec.get("SpecID") != null) {
                    specId = itemGradeAndItemSpec.get("SpecID").toString();

                    samId = sampleId;
                }
            }
        }


        if ("0".equals(gradeId) && "0".equals(specId)) {
            log.error("查询 协会对应的规格信息为空！itemID =" + "materialsSpecs =" + materialsSpecs);
            throw new RuntimeException("查询 协会对应的规格信息为空！itemID =" + "materialsSpecs =" + materialsSpecs);
        }*/


        importList.setGradeId(gradeId);
        importList.setSpecId(specId);
        importList.setSampleID(sampleId);

        importListMapper.updateImportListByImportId(importList);

        log.info("修改原材料进料数据结束...");
    }

}
